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


当前回答

三重引用的评论是这个问题的一个有趣的子主题。PEP 257为文档字符串指定了三引号。我使用谷歌代码搜索做了一个快速检查,发现Python中的三双引号大约是三单引号的10倍——在谷歌代码索引中出现1.3M vs 131K次。在多行情况下,如果你的代码使用三双引号,人们可能会更熟悉。

其他回答

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

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

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

三重引用的评论是这个问题的一个有趣的子主题。PEP 257为文档字符串指定了三引号。我使用谷歌代码搜索做了一个快速检查,发现Python中的三双引号大约是三单引号的10倍——在谷歌代码索引中出现1.3M vs 131K次。在多行情况下,如果你的代码使用三双引号,人们可能会更熟悉。

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