简体   繁体   English

如何打印包含新行的列表项?

[英]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?当我们在print()命令之外生成列表时是否可能?

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.上面的解决方案在棘手的情况下不起作用,例如,如果字符串是"1\\\\n2"它会替换,但它不应该。 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 .否则,您将看到它们为\\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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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