How to print list items which contain new line?

后端 未结 4 711
感动是毒
感动是毒 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:15

    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]
    
    0 讨论(0)
  • 2021-01-29 12:21

    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.

    0 讨论(0)
  • 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)))
    
    0 讨论(0)
  • 2021-01-29 12:30

    Try this:

    s = ["1\n2"]
    print("['{}']".format(s[0]))
    => ['1
       2']
    
    0 讨论(0)
提交回复
热议问题