Single vs. Double Quotes in Python
Python's documentation allows the interchangeable use of single and double quotes for string literals. However, stylistic preferences may arise between the two.
Stylistic Guidelines
-
Use double quotes ("") for strings intended for interpolation or those representing natural language messages.
-
Use single quotes ('') for brief, symbol-like strings.
Exceptions:
-
Double quotes should be used when strings contain single quotes.
-
Single quotes should be used when strings contain double quotes.
Additional Considerations
-
Triple double quotes (""") are employed for docstrings and raw string literals for regular expressions.
-
Single quotes are often preferred for string variable declarations to avoid potential conflicts with the "in" keyword.
Example:
Consider the following code:
LIGHT_MESSAGES = {
'English': "There are %(number_of_lights)s lights.",
'Pirate': "Arr! Thar be %(number_of_lights)s lights."
}
def lights_message(language, number_of_lights):
return LIGHT_MESSAGES[language] % locals()
def is_pirate(message):
"""Return True if the given message sounds piratical."""
return re.search(r"(?i)(arr|avast|yohoho)!", message) is not None
In this example:
- Double quotes are used for strings intended for interpolation (e.g., "There are %(number_of_lights)s lights.").
- Single quotes are used for the brief symbol-like string in the regex pattern (r"(?i)(arr|avast|yohoho)!").
- Triple double quotes are used for the docstring in the is_pirate function.
The above is the detailed content of When Should I Use Single vs. Double Quotes in Python?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn