在PHP中,包含在“双引号”中的字符串将被解析为要替换的变量,而包含在“单引号”中的字符串则不会。在Python中,这也适用吗?
发布于 2008-09-27 14:58:26
在其他一些语言中,如果使用单引号,则不会解释元字符。以Ruby中的示例为例:
irb(main):001:0> puts "string1\nstring2"
string1
string2
=> nil
irb(main):002:0> puts 'string1\nstring2'
string1\nstring2
=> nil
在Python中,如果您希望按字面理解字符串,则可以使用原始字符串( 'r‘字符前面的字符串):
>>> print 'string1\nstring2'
string1
string2
>>> print r'string1\nstring2'
string1\nstring2
发布于 2008-09-27 14:55:07
Python中的单引号字符串和双引号字符串是相同的。唯一的区别是单引号字符串可以包含未转义的双引号字符,反之亦然。例如:
'a "quoted" word'
"another 'quoted' word"
此外,还有三重引号的字符串,它允许对引号字符和换行符进行非转义。
您可以使用命名说明符和locals()内置替换字符串中的变量:
name = 'John'
lastname = 'Smith'
print 'My name is %(name)s %(lastname)s' % locals() # prints 'My name is John Smith'
发布于 2016-01-03 19:25:19
交互式Python解释器更喜欢单引号:
>>> "text"
'text'
>>> 'text'
'text'
这可能会让初学者感到困惑,所以我坚持使用单引号(除非您有不同的编码标准)。
https://stackoverflow.com/questions/143714
复制相似问题