根据文档,它们几乎是可以互换的。是否有使用其中一种而不是另一种的风格原因?
当前回答
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次。在多行情况下,如果你的代码使用三双引号,人们可能会更熟悉。
我选择使用双引号,因为它们更容易看到。
我只是用我当时喜欢的东西;这很方便,能够在两者之间切换心血来潮!
当然,在引用引用字符时,在两者之间切换可能并不是那么异想天开……
引用官方文件https://docs.python.org/2.0/ref/strings.html:
简单地说:字符串字面量可以包含在匹配的单引号(')或双引号(")中。
所以没有区别。相反,人们会告诉你选择与上下文相匹配的风格,并保持一致。我同意——补充说,试图为这类事情提出“惯例”是毫无意义的,因为你最终只会让任何新人感到困惑。
这可能是一种风格上的偏好。我刚刚检查了PEP 8,没有看到任何提到单引号和双引号。
我更喜欢单引号,因为它只有一个按键,而不是两个。也就是说,我不需要捣碎shift键来做单引号。
推荐文章
- 如何在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:给定列的数据帧行之和