根据文档,它们几乎是可以互换的。是否有使用其中一种而不是另一种的风格原因?
当前回答
三重引用的评论是这个问题的一个有趣的子主题。PEP 257为文档字符串指定了三引号。我使用谷歌代码搜索做了一个快速检查,发现Python中的三双引号大约是三单引号的10倍——在谷歌代码索引中出现1.3M vs 131K次。在多行情况下,如果你的代码使用三双引号,人们可能会更熟悉。
其他回答
我以前更喜欢',特别是'文档字符串',因为我发现''' '这会产生一些绒毛''' '。此外,在我的瑞士德语键盘上,'也可以不用Shift键输入。
为了符合PEP 257,我已经将“”“文档字符串”“”改为使用三引号。
我使用双引号是因为我已经在大多数语言(c++, Java, VB…)中这样做了很多年,除了Bash,因为我也在普通文本中使用双引号,因为我使用的是(经过修改的)非英语键盘,其中两个字符都需要shift键。
' = "
/ = \ = \\
例子:
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'
据我所知没有。尽管如果你看一些代码," "通常用于文本字符串(我猜'在文本中比'更常见),' '出现在hashkey和类似的东西中。
推荐文章
- 如何在matplotlib更新一个情节
- TypeError: ` NoneType `对象在Python中不可迭代
- 如何在Vim注释掉一个Python代码块
- python标准库中的装饰符(特别是@deprecated)
- 如何从外部访问本地Django web服务器
- 删除字符串的最后3个字符
- 在python中执行no-op的标准方法是什么?
- 如何从生成器构建numpy数组?
- 什么时候我应该(不)想要在我的代码中使用熊猫apply() ?
- 数据类vs类型。NamedTuple主要用例
- 如何从macOS完全卸载蟒蛇
- 是否有可能键入提示一个lambda函数?
- 'dict'对象没有has_key属性
- 使用Pandas groupby连接来自几行的字符串
- Pandas:给定列的数据帧行之和