根据文档,它们几乎是可以互换的。是否有使用其中一种而不是另一种的风格原因?
当前回答
我的目标是最小化像素和惊喜。我通常更喜欢' in order to最小化像素,但是' '如果字符串有撇号,同样是为了最小化像素。然而,对于文档字符串,我更喜欢"""而不是" ',因为后者是不标准的、不常见的,因此令人惊讶。如果现在我有一堆字符串,我使用“根据上面的逻辑,但也可以使用一个',我可能仍然使用”,以保持一致性,只是为了尽量减少惊喜。
也许用以下方式来思考像素最小化哲学会有所帮助。你更希望英文字符看起来像A B C还是AA BB CC?后一种选择浪费了50%的非空像素。
其他回答
您的团队的品味或项目的编码指南。
例如,如果您处于多语言环境中,您可能希望鼓励对字符串使用与其他语言相同类型的引号。除此之外,我个人最喜欢的是
' = "
/ = \ = \\
例子:
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中的路径而言,正斜杠的解释是相同的。显然字符串本身是不同的。但我不能保证它们在外部设备上也能以这种方式处理。
据我所知没有。尽管如果你看一些代码," "通常用于文本字符串(我猜'在文本中比'更常见),' '出现在hashkey和类似的东西中。
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++, Java, VB…)中这样做了很多年,除了Bash,因为我也在普通文本中使用双引号,因为我使用的是(经过修改的)非英语键盘,其中两个字符都需要shift键。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象