根据文档,它们几乎是可以互换的。是否有使用其中一种而不是另一种的风格原因?
当前回答
我喜欢在用于插值的字符串或自然语言消息的字符串周围使用双引号,而对于像符号一样的小字符串使用单引号,但如果字符串包含引号,或者如果我忘记了,就会破坏规则。我对文档字符串使用三双引号,对正则表达式使用原始字符串字面量,即使它们不需要。
例如:
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 a language-appropriate string reporting the light count."""
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
其他回答
我支持威尔:
文本的双引号 任何行为类似于标识符的东西都可以使用单引号 regexp的双引号原始字符串字面量 文档字符串的三倍双引号
即使这意味着要逃跑,我也会坚持下去。
我从单引号标识符中获得了最大的价值。其余的实践只是为了给那些单引号标识符留出一些空间。
在Perl中,当您有一个不需要插入变量或转义字符(如\n, \t, \r等)的字符串时,您希望使用单引号。
PHP与Perl做了相同的区分:单引号中的内容不会被解释(甚至\n也不会被转换),而双引号中可以包含变量并将其值打印出来。
恐怕Python没有。从技术上看,Python中没有$令牌(或类似的)将名称/文本与变量分开。毕竟,这两个特性都使Python更具可读性,不那么令人困惑。在Python中,单引号和双引号可以互换使用。
Python使用引号,就像这样:
mystringliteral1="this is a string with 'quotes'"
mystringliteral2='this is a string with "quotes"'
mystringliteral3="""this is a string with "quotes" and more 'quotes'"""
mystringliteral4='''this is a string with 'quotes' and more "quotes"'''
mystringliteral5='this is a string with \"quotes\"'
mystringliteral6='this is a string with \042quotes\042'
mystringliteral6='this is a string with \047quotes\047'
print mystringliteral1
print mystringliteral2
print mystringliteral3
print mystringliteral4
print mystringliteral5
print mystringliteral6
输出如下:
this is a string with 'quotes'
this is a string with "quotes"
this is a string with "quotes" and more 'quotes'
this is a string with 'quotes' and more "quotes"
this is a string with "quotes"
this is a string with 'quotes'
这可能是一种风格上的偏好。我刚刚检查了PEP 8,没有看到任何提到单引号和双引号。
我更喜欢单引号,因为它只有一个按键,而不是两个。也就是说,我不需要捣碎shift键来做单引号。
"If you're going to use apostrophes,
^
you'll definitely want to use double quotes".
^
出于这个简单的原因,我总是在外面使用双引号。总是
说到无用,如果你必须使用转义字符来表示撇号,那么用'简化字符串文字有什么好处呢?读小说会冒犯程序员吗?我无法想象高中英语课对你来说有多痛苦!
推荐文章
- 如何在matplotlib更新一个情节
- TypeError: ` NoneType `对象在Python中不可迭代
- 如何在Vim注释掉一个Python代码块
- python标准库中的装饰符(特别是@deprecated)
- 如何从外部访问本地Django web服务器
- 删除字符串的最后3个字符
- 在python中执行no-op的标准方法是什么?
- 如何从生成器构建numpy数组?
- 什么时候我应该(不)想要在我的代码中使用熊猫apply() ?
- 数据类vs类型。NamedTuple主要用例
- 如何从macOS完全卸载蟒蛇
- 是否有可能键入提示一个lambda函数?
- 'dict'对象没有has_key属性
- 使用Pandas groupby连接来自几行的字符串
- Pandas:给定列的数据帧行之和