Python - Join with newline
在python控制台中,当我键入:
1 2 | >>>" ".join(['I', 'would', 'expect', 'multiple', 'lines']) |
给予:
1 2 3 4 5 | 'I would expect multiple lines' |
虽然我希望看到这样的输出:
1 2 3 4 5 | I would expect multiple lines |
我这里缺什么?
控制台正在打印表示,而不是字符串本身。
如果你以
有关字符串和字符串表示形式之间的差异的详细信息,请参阅此问题。这种表示法非常简单,您可以在源代码中键入代码来获取该字符串。
你忘了把结果告诉
在py2.x中,你应该
1 2 3 4 5 6 7 | >>> print" ".join(['I', 'would', 'expect', 'multiple', 'lines']) I would expect multiple lines |
在py3.x中,print是一个函数,所以应该这样做
1 2 | print(" ".join(['I', 'would', 'expect', 'multiple', 'lines'])) |
现在这是个简短的回答。python解释器实际上是一个repl,它总是显示字符串的表示,而不是实际显示的输出。代表性就是你能从
1 2 3 4 5 6 7 | >>> print repr(" ".join(['I', 'would', 'expect', 'multiple', 'lines'])) 'I would expect multiple lines' |
您需要
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> x =" ".join(['I', 'would', 'expect', 'multiple', 'lines']) >>> x # this is the value, returned by the join() function 'I would expect multiple lines' >>> print x # this prints your string (the type of output you want) I would expect multiple lines |
当你用这个
would
expect
multiple
lines'
1 2 3 4 5 | I would expect multiple lines |
你必须打印它:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | In [22]:" ".join(['I', 'would', 'expect', 'multiple', 'lines']) Out[22]: 'I would expect multiple lines' In [23]: print" ".join(['I', 'would', 'expect', 'multiple', 'lines']) I would expect multiple lines |