2016-01-06 68 views
1

我在学习Python的艰难之路。这里是exercise9的常见学生问题中的内容Python中格式化程序%r和 n发生了什么?

为什么\ n换行符在我使用%r时不起作用?

这就是%r格式化的工作方式,它以您写它(或接近它)的方式打印它。这是用于调试的“原始”格式

然后我尝试了它,但它对我有用!

我的代码:

# test %r with \n 
print "test\n%r\n%r" % ("with", "works?") 

# change a way to test it 
print "%r\n%r" % ("with", "works?") 

输出:

test 
'with' 
'works?' 
'with' 
'works?' 

它混淆了我,是有什么错我的测试或这本书吗? 你能告诉我一些例子吗?非常感谢。

+3

你想到了'\ N'不被解释为换行符?您正在将字符串语法本身插入的值混淆。 –

回答

3

这不是你会看到%r的效果。把转义字符如换行符('\n')到字符串将取代%r

>>> print "%r\n%r" % ("with\n", "works?") 
'with\n' 
'works?' 

现在使用%s,它与str()表示,而不是repr()代表取代,看出区别:

>>> print "%s\n%s" % ("with\n", "works?") 
with 

works? 
1

你很混淆原始字符串文字%rrepr())字符串格式化程序。它们不是同一件事。

你定义一个字符串:

'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' 
+0

非常感谢。 –