简体   繁体   中英

How to print list items which contain new line?

These commands:

l = ["1\n2"]    
print(l)

print

['1\n2']

I want to print

['1
2']

Is it possible when we generate the list outside of the print() command?

A first attempt:

l = ["1\n2"]
print(repr(l).replace('\\n', '\n'))

The solution above doesn't work in tricky cases, for example if the string is "1\\\\n2" it replaces, but it shouldn't. Here is how to fix it:

import re
l = ["1\n2"]
print(re.sub(r'\\n|(\\.)', lambda match: match.group(1) or '\n', repr(l)))

Only if you are printing the element itself (or each element) and not the whole list:

>>> a = ['1\n2']
>>> a
['1\n2']
>>> print a
['1\n2']
>>> print a[0]
1
2

When you try to just print the whole list, it prints the string representation of the list. Newlines belong to individual elements so get printed as newlines only when print that element. Otherwise, you will see them as \\n .

You should probably use this, if you have more than one element

>>> test = ['1\n2', '3', '4\n5']
>>> print '[{0}]'.format(','.join(test))
[1
2,3,4
5]

Try this:

s = ["1\n2"]
print("['{}']".format(s[0]))
=> ['1
   2']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM