Python-加入换行符


88

在Python控制台中,当我输入时:

>>> "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])

给出:

'I\nwould\nexpect\nmultiple\nlines'

虽然我希望看到这样的输出:

I
would
expect
multiple
lines

我在这里想念什么?

Answers:


88

控制台正在打印表示形式,而不是字符串本身。

如果使用前缀print,您将获得期望的结果。

有关字符串和字符串表示形式之间的区别的详细信息,请参见此问题。超级简化了,该表示形式就是您在源代码中键入以获取该字符串的内容。


41

您忘记print了结果。你得到的是PRE(P)L,而不是实际的打印结果。

在Py2.x中,您应该这样

>>> print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines

在Py3.X中,打印是一种功能,因此您应该

print("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))

现在,这是一个简短的答案。您的Python解释器实际上是REPL,始终显示字符串的表示形式,而不是实际显示的输出。repr陈述就是您将获得的陈述

>>> print repr("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))
'I\nwould\nexpect\nmultiple\nlines'

13

您需要print获取该输出。
你应该做

>>> x = "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
>>> x                   # this is the value, returned by the join() function
'I\nwould\nexpect\nmultiple\nlines'
>>> print x    # this prints your string (the type of output you want)
I
would
expect
multiple
lines

4

您必须打印它:

In [22]: "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
Out[22]: 'I\nwould\nexpect\nmultiple\nlines'

In [23]: print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines

4

当您用它打印时,print 'I\nwould\nexpect\nmultiple\nlines'您将得到:

I
would
expect
multiple
lines

\n是专门用于标记结束-OF-TEXT换行符。它表示行或文本的结尾。许多语言(例如C,C ++等)都具有此特征。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.