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


当前回答

"If you're going to use apostrophes, 
       ^

you'll definitely want to use double 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中的路径而言,正斜杠的解释是相同的。显然字符串本身是不同的。但我不能保证它们在外部设备上也能以这种方式处理。

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'
"If you're going to use apostrophes, 
       ^

you'll definitely want to use double quotes".
   ^

出于这个简单的原因,我总是在外面使用双引号。总是

说到无用,如果你必须使用转义字符来表示撇号,那么用'简化字符串文字有什么好处呢?读小说会冒犯程序员吗?我无法想象高中英语课对你来说有多痛苦!

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

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

据我所知没有。尽管如果你看一些代码," "通常用于文本字符串(我猜'在文本中比'更常见),' '出现在hashkey和类似的东西中。