根据文档,它们几乎是可以互换的。是否有使用其中一种而不是另一种的风格原因?


当前回答

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'

其他回答

我支持威尔:

文本的双引号 任何行为类似于标识符的东西都可以使用单引号 regexp的双引号原始字符串字面量 文档字符串的三倍双引号

即使这意味着要逃跑,我也会坚持下去。

我从单引号标识符中获得了最大的价值。其余的实践只是为了给那些单引号标识符留出一些空间。

您的团队的品味或项目的编码指南。

例如,如果您处于多语言环境中,您可能希望鼓励对字符串使用与其他语言相同类型的引号。除此之外,我个人最喜欢的是

引用官方文件https://docs.python.org/2.0/ref/strings.html:

简单地说:字符串字面量可以包含在匹配的单引号(')或双引号(")中。

所以没有区别。相反,人们会告诉你选择与上下文相匹配的风格,并保持一致。我同意——补充说,试图为这类事情提出“惯例”是毫无意义的,因为你最终只会让任何新人感到困惑。

据我所知没有。尽管如果你看一些代码," "通常用于文本字符串(我猜'在文本中比'更常见),' '出现在hashkey和类似的东西中。

我使用双引号是因为我已经在大多数语言(c++, Java, VB…)中这样做了很多年,除了Bash,因为我也在普通文本中使用双引号,因为我使用的是(经过修改的)非英语键盘,其中两个字符都需要shift键。