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


当前回答

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'

其他回答

我只是用我当时喜欢的东西;这很方便,能够在两者之间切换心血来潮!

当然,在引用引用字符时,在两者之间切换可能并不是那么异想天开……

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

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

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

就我个人而言,我坚持两者之一。没关系。当你们合作的时候,为这两句话提供自己的意思只会让其他人感到困惑。

这可能是一种风格上的偏好。我刚刚检查了PEP 8,没有看到任何提到单引号和双引号。

我更喜欢单引号,因为它只有一个按键,而不是两个。也就是说,我不需要捣碎shift键来做单引号。

我选择使用双引号,因为它们更容易看到。