Python - 加入换行符

TTT*_*TTT 71 python string

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

>>> "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
Run Code Online (Sandbox Code Playgroud)

得到:

'I\nwould\nexpect\nmultiple\nlines'
Run Code Online (Sandbox Code Playgroud)

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

I
would
expect
multiple
lines
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

unw*_*ind 71

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

如果你加上前缀print,你会得到你期望的.

有关字符串与字符串表示之间差异的详细信息,请参阅此问题.超简化,表示是您在源代码中键入以获取该字符串的内容.


Abh*_*jit 37

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

在Py2.x中你应该这样

>>> print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines
Run Code Online (Sandbox Code Playgroud)

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

print("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))
Run Code Online (Sandbox Code Playgroud)

现在这是简短的回答.您的Python解释器实际上是一个REPL,它始终显示字符串的表示形式而不是实际显示的输出.表达就是你对repr声明的看法

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


pra*_*nsg 10

你需要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
Run Code Online (Sandbox Code Playgroud)


roo*_*oot 5

你必须打印它:

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
Run Code Online (Sandbox Code Playgroud)