我不懂Python原始字符串

时间:2013-04-24 07:22:51

标签: python

python doc说:

  

如果我们将字符串文字设为“原始”字符串,\n序列不会转换为换行符,但行末尾的反斜杠和源代码中的换行符都包含在字符串作为数据。因此,例如:

我不太明白,因为它说源中的换行符包含在字符串中作为数据,但\n只是按字面意思打印,如下例所示。

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

print(hello)

任何类型的帮助都可以帮助我理解但是行尾的反斜杠和源代码中的换行符都作为数据包含在字符串中吗?

1 个答案:

答案 0 :(得分: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']
相关问题