你很混淆原始字符串文字与%r
(repr()
)字符串格式化程序。它们不是同一件事。
你定义一个字符串:
'This is a string with a newline\n'
这将产生一个字符串对象。然后,您将该字符串对象与%
运算符一起使用,该运算符可让您用任何%
运算符的右侧替换任何%
标记的占位符。 %r
占位符使用repr()
为给定对象生成一个字符串并将该字符串插入到插槽中。
如果您预计\n
被解释为一个反斜杠和独立n
字符,使用原始字符串字面,通过r
前缀:
r'This is a string with a literal backslash and letter n: \n'
如果您预计%r
产生逃脱(蟒蛇)语法,将换行符置于右侧的值; repr()
串产生字符串文字语法:
'This will show the string in Python notation: %r' % ('String with \n newline',)
这需要的repr('String with \n newline')
输出,并将其插入到字符串:
>>> 'String with \n newline'
'String with \n newline'
>>> repr('String with \n newline')
"'String with \\n newline'"
>>> print repr('String with \n newline')
'String with \n newline'
>>> 'This will show the string in Python notation: %r' % ('String with \n newline',)
"This will show the string in Python notation: 'String with \\n newline'"
>>> print 'This will show the string in Python notation: %r' % ('String with \n newline',)
This will show the string in Python notation: 'String with \n newline'
你想到了'\ N'不被解释为换行符?您正在将字符串语法本身插入的值混淆。 –