How to print list items which contain new line?

后端 未结 4 816
感动是毒
感动是毒 2021-01-29 12:07

These commands:

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

print

[\'1\\n2\']

I want to print

[\'1
2\']
         


        
4条回答
  •  我在风中等你
    2021-01-29 12:29

    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)))
    

提交回复
热议问题