2013-04-24 228 views
0

蟒蛇医生说:我不明白Python原始字符串

如果我们让字符串字面量“原始”的字符串,\n序列不被转换为新行,但是反斜杠在该行的末尾,以及源代码中的换行符都作为数据包含在字符串中。因此,例如:

我不太明白,因为它说源中的换行符inclued字符串作为数据中,但\n只是如下面的例子字面上打印。

hello = r"This is a rather long string containing\n\ 
several lines of text much as you would do in C." 

print(hello) 

任何助手可以帮助我了解但反斜线在该行的末尾,并在源换行字符,都包含字符串作为数据?

回答

2

你既包括\n(两个字符)字符串中的换行:

>>> hello 
'This is a rather long string containing\\n\\\nseveral lines of text much as you would do in C.' 

减少它只是\n\部分(与第二斜线后换行:

>>> hello = r'\n\ 
... ' 
>>> hello 
'\\n\\\n' 
>>> len(hello) 
4 
>>> list(hello) 
['\\', 'n', '\\', '\n'] 

这里有4个字符,一个反斜杠(表示中使其成为一个有效的Python字符串的两倍),一个n,另一个反斜杠和一个换行

您可以进一步细分;在源字面换行符之前反斜杠创建字符串两者反斜杠和换行符:

>>> hello = r'\ 
... ' 
>>> hello 
'\\\n' 
>>> len(hello) 
2 
>>> list(hello) 
['\\', '\n'] 

在另一方面的原始文字r'\n'创建反斜线和文字字符n

>>> hello = r'\n' 
>>> hello 
'\\n' 
>>> len(hello) 
2 
>>> list(hello) 
['\\', 'n']