Join with newline
In the Python console, when I type:
>>> "n".join(['I', 'would', 'expect', 'multiple', 'lines'])
Gives:
'Inwouldnexpectnmultiplenlines'
Though I'd expect to see such an output:
I
would
expect
multiple
lines
What am I missing here?
The console is printing the representation, not the string itself.
If you prefix with print
, you'll get what you expect.
See this question for details about the difference between a string and the string's representation. Super-simplified, the representation is what you'd type in source code to get that string.
You forgot to print
the result. What you get is the P
in RE(P)L
and not the actual printed result.
In Py2.x you should so something like
>>> print "n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines
and in Py3.X, print is a function, so you should do
print("n".join(['I', 'would', 'expect', 'multiple', 'lines']))
Now that was the short answer. Your Python Interpreter, which is actually a REPL, always displays the representation of the string rather than the actual displayed output. Representation is what you would get with the repr
statement
>>> print repr("n".join(['I', 'would', 'expect', 'multiple', 'lines']))
'Inwouldnexpectnmultiplenlines'
You need to print
to get that output.
You should do
>>> x = "n".join(['I', 'would', 'expect', 'multiple', 'lines'])
>>> x # this is the value, returned by the join() function
'Inwouldnexpectnmultiplenlines'
>>> print x # this prints your string (the type of output you want)
I
would
expect
multiple
lines
链接地址: http://www.djcxy.com/p/31798.html
上一篇: 如何将字符串转换为Python中的整数?
下一篇: 加入换行符