Python-使用换行符连接
在Python控制台中,当我键入:Python-使用换行符连接,python,string,Python,String,在Python控制台中,当我键入: >>> "\n".join(['I', 'would', 'expect', 'multiple', 'lines']) 给出: 'I\nwould\nexpect\nmultiple\nlines' 虽然我希望看到这样的输出: I would expect multiple lines 我在这里遗漏了什么?您必须打印它: In [22]: "\n".join(['I', 'would', 'expect', 'multiple', '
>>> "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
给出:
'I\nwould\nexpect\nmultiple\nlines'
虽然我希望看到这样的输出:
I
would
expect
multiple
lines
我在这里遗漏了什么?您必须打印它:
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
您忘了打印结果。您得到的是中的
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']))
>>> 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
这是一个简短的答案。Python解释器实际上是一个REPL,它总是显示字符串的表示形式,而不是实际显示的输出。表示是使用repr
语句可以得到的结果
>>> print repr("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))
'I\nwould\nexpect\nmultiple\nlines'
控制台正在打印表示,而不是字符串本身 如果您以
print
作为前缀,您将得到预期的结果
有关字符串和字符串表示形式之间差异的详细信息,请参见。超级简化,表示形式就是您在源代码中键入的字符串。当您使用此
打印“I\nwould\nexpect\nmultiple\nlines”时,您将得到:
I
would
expect
multiple
lines
\n
是专门用于标记文本结尾的新行字符。它表示行或文本的结尾。这种特性被许多语言共享,如C、C++等。 < P>你需要<代码>打印< /代码>以获得输出。
你应该这样做
print("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))
>>> 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