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


当前回答

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

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

其他回答

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

在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'

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

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

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