格式化程序%r和\ n在Python中发生了什么?

时间:2016-01-06 13:38:50

标签: python string-formatting

我正在学习如何艰难地学习Python。以下是exercise9的普通学生问题

中的内容

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

这就是%r格式的工作原理,它以你编写它(或接近它)的方式打印它。它是" raw"调试格式

然后我尝试了,但它适用于我!

我的代码:

# 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?'

让我感到困惑,我的测试或书籍出了什么问题? 你能告诉我一些例子吗?非常感谢。

2 个答案:

答案 0 :(得分:3)

这不是你会看到SELECT firstname, lastname, email, phone, absences FROM meetings_attendance, members WHERE absences = ( SELECT COUNT(*) FROM meetings_attendance WHERE attendance = "Absent" ) AND members.id = meetings_attendance.members_id 的影响的地方。将包含换行符(IDictionary<int, string> dict = new Dictionary<int, string> { { 1, "Axe" }, { 6, "WarHammer" }, { 2, "Knife" }, { 9, "Gun" } }; var list = dict.Where(x => x.Key > 5).Select(x=> x.Value) .ToList(); )的转义字符放入将替换%r的字符串中:

'\n'

现在使用%r取代>>> print "%r\n%r" % ("with\n", "works?") 'with\n' 'works?' 表示而不是%s表示,以查看差异:

str()

答案 1 :(得分:1)

您将原始字符串文字++*++var%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' 生成转义(Python)语法,请将换行符放在右侧的值中; %r字符串生成字符串文字语法:

repr()

这将获取'This will show the string in Python notation: %r' % ('String with \n newline',) 的输出并将其插入到字符串中:

repr('String with \n newline')