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


当前回答

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

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

其他回答

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

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

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

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'

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

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

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

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

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