根据文档,它们几乎是可以互换的。是否有使用其中一种而不是另一种的风格原因?
当前回答
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 257为文档字符串指定了三引号。我使用谷歌代码搜索做了一个快速检查,发现Python中的三双引号大约是三单引号的10倍——在谷歌代码索引中出现1.3M vs 131K次。在多行情况下,如果你的代码使用三双引号,人们可能会更熟悉。
我的目标是最小化像素和惊喜。我通常更喜欢' in order to最小化像素,但是' '如果字符串有撇号,同样是为了最小化像素。然而,对于文档字符串,我更喜欢"""而不是" ',因为后者是不标准的、不常见的,因此令人惊讶。如果现在我有一堆字符串,我使用“根据上面的逻辑,但也可以使用一个',我可能仍然使用”,以保持一致性,只是为了尽量减少惊喜。
也许用以下方式来思考像素最小化哲学会有所帮助。你更希望英文字符看起来像A B C还是AA BB CC?后一种选择浪费了50%的非空像素。
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'
' = "
/ = \ = \\
例子:
f = open('c:\word.txt', 'r')
f = open("c:\word.txt", "r")
f = open("c:/word.txt", "r")
f = open("c:\\\word.txt", "r")
结果是一样的
>>不,它们不一样。 一个反斜杠将转义字符。在这个例子中,你只是碰巧走运,因为\k和\w不是有效的转义,就像\t或\n或\\或\"
如果你想使用单个反斜杠(并将它们解释为反斜杠),那么你需要使用一个“原始”字符串。你可以在字符串前面加上一个'r'来做到这一点
im_raw = r'c:\temp.txt'
non_raw = 'c:\\temp.txt'
another_way = 'c:/temp.txt'
就Windows中的路径而言,正斜杠的解释是相同的。显然字符串本身是不同的。但我不能保证它们在外部设备上也能以这种方式处理。