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


当前回答

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键来做单引号。

我以前更喜欢',特别是'文档字符串',因为我发现''' '这会产生一些绒毛''' '。此外,在我的瑞士德语键盘上,'也可以不用Shift键输入。

为了符合PEP 257,我已经将“”“文档字符串”“”改为使用三引号。

我通常使用双引号,但不是为了任何特定的原因——可能只是出于Java的习惯。

我猜在内联文字字符串中,您更可能需要撇号而不是双引号。

我支持威尔:

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

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

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

如果字符串包含其中一个,则应该使用另一个。例如,“你能做这个”,或者“他说了“嗨!”。除此之外,你应该尽可能保持一致(在一个模块内,在一个包内,在一个项目内,在一个组织内)。

如果您的代码将被使用C/ c++的人阅读(或者如果您在这些语言和Python之间切换),那么使用“用于单字符字符串,使用“”用于较长的字符串可能有助于简化转换。(同样也适用于其他不可互换的语言)。

我在野外看到的Python代码倾向于“over”,但只是略微倾向于这样。唯一的例外是,“”“这些”“”比“这些”更常见,从我所看到的。