Python-使用 newline 连接

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

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

Gives:

'I\nwould\nexpect\nmultiple\nlines'

尽管我期待看到这样的结果:

I
would
expect
multiple
lines

我错过了什么?

185310 次浏览

你必须打印出来:

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

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

在 Py2.x 中,你应该这样做

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

在 Py3.X 中,print 是一个函数,所以应该这样做

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

这就是简短的回答。Python Interpreter 实际上是一个 REPL,它总是显示字符串的表示形式,而不是实际显示的输出。表示是使用 repr语句得到的

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

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

如果使用 print作为前缀,就会得到所期望的结果。

有关字符串和字符串表示形式之间差异的详细信息,请参阅 这个问题。超级简化的表示就是您在源代码中键入以获得该字符串的内容。

当你用这个 print 'I\nwould\nexpect\nmultiple\nlines'打印时,你会得到:

I
would
expect
multiple
lines

\n是一个新的行字符,专门用于标记 END-OF-TEXT。它表示行或文本的结束。这个特性被许多语言如 C,C + + 等共享。

You need to print to get that output.
你应该这么做

>>> 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

Repr ()函数返回给定对象的可打印表示形式,这对于 Python 中的 evalStr ()或 exec 是至关重要的; 例如,您想了解 Python 的 Zen:

eng.execString('from this import *');
println('import this:'+CRLF+
stringReplace(eng.EvalStr('repr("".join([d.get(c,c) for c in s]))'),'\n',CRLF,[rfReplaceAll]));