Dav*_*idM 61 python string quotes double-quotes
在PHP中,用"双引号"括起来的字符串将被解析为要替换的变量,而用"单引号"括起来的字符串则不会.在Python中,这也适用吗?
Bry*_*ley 38
Python是少数(?)语言中的一种,其中'和'具有相同的功能.我的选择通常取决于内部.如果我要引用其中包含单引号的字符串,我将使用双引号反之亦然,减少必须逃避字符串中的字符.
例子:
"this doesn't require escaping the single quote"
'she said "quoting is easy in python"'
Run Code Online (Sandbox Code Playgroud)
这在python文档的"String Literals"页面上有记录:
在某些其他语言中,如果使用单引号,则不会解释元字符.以Ruby为例:
irb(main):001:0> puts "string1\nstring2"
string1
string2
=> nil
irb(main):002:0> puts 'string1\nstring2'
string1\nstring2
=> nil
Run Code Online (Sandbox Code Playgroud)
在Python中,如果你想要字面意思地使用字符串,你可以使用原始字符串(前面带有"r"字符的字符串):
>>> print 'string1\nstring2'
string1
string2
>>> print r'string1\nstring2'
string1\nstring2
Run Code Online (Sandbox Code Playgroud)
Python 中的单引号和双引号字符串是相同的。唯一的区别是单引号字符串可以包含未转义的双引号字符,反之亦然。例如:
'a "quoted" word'
"another 'quoted' word"
Run Code Online (Sandbox Code Playgroud)
另外,还有三引号字符串,它允许引号字符和换行符不被转义。
您可以使用命名说明符和内置的 locals() 替换字符串中的变量:
name = 'John'
lastname = 'Smith'
print 'My name is %(name)s %(lastname)s' % locals() # prints 'My name is John Smith'
Run Code Online (Sandbox Code Playgroud)
交互式 Python 解释器更喜欢单引号:
>>> "text"
'text'
>>> 'text'
'text'
Run Code Online (Sandbox Code Playgroud)
这可能会让初学者感到困惑,所以我会坚持使用单引号(除非您有不同的编码标准)。
" 和 ' 字符串引用之间的区别仅在于风格 - 只不过其中一个不需要在字符串内容中转义另一个。
PEP8建议采用一致的规则,PEP257建议文档字符串使用三重双引号。
在Python中,单引号字符串和双引号字符串是相同的。本 PEP 并未对此提出建议。选择一个规则并遵守它。但是,当字符串包含单引号或双引号字符时,请使用另一个以避免字符串中出现反斜杠。它提高了可读性。
对于三引号字符串,请始终使用双引号字符,以与 PEP 257 中的文档字符串约定保持一致。
然而,广泛使用的做法是对自然语言字符串(包括插值)更喜欢使用双引号 - 因此任何可能成为 I18N 候选者的东西。以及技术字符串的单引号:符号、字符、路径、命令行选项、技术正则表达式……
(例如,在准备 I18N 代码时,我运行半自动 REGEX 快速转换双引号字符串以使用 eg gettext)
| 归档时间: |
|
| 查看次数: |
53799 次 |
| 最近记录: |