根据文档,它们几乎是可以互换的。是否有使用其中一种而不是另一种的风格原因?
当前回答
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和类似的东西中。
您的团队的品味或项目的编码指南。
例如,如果您处于多语言环境中,您可能希望鼓励对字符串使用与其他语言相同类型的引号。除此之外,我个人最喜欢的是
如果字符串包含其中一个,则应该使用另一个。例如,“你能做这个”,或者“他说了“嗨!”。除此之外,你应该尽可能保持一致(在一个模块内,在一个包内,在一个项目内,在一个组织内)。
如果您的代码将被使用C/ c++的人阅读(或者如果您在这些语言和Python之间切换),那么使用“用于单字符字符串,使用“”用于较长的字符串可能有助于简化转换。(同样也适用于其他不可互换的语言)。
我在野外看到的Python代码倾向于“over”,但只是略微倾向于这样。唯一的例外是,“”“这些”“”比“这些”更常见,从我所看到的。
就我个人而言,我坚持两者之一。没关系。当你们合作的时候,为这两句话提供自己的意思只会让其他人感到困惑。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录