How to split a python string on new line characters

前端 未结 2 752
北荒
北荒 2020-12-03 06:22

In python3 in Win7 I read a web page into a string.

I then want to split the string into a list at newline characters.

I can\'t enter the newline into my cod

相关标签:
2条回答
  • 2020-12-03 07:03

    a.txt

    this is line 1
    this is line 2
    

    code:

    Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
    [GCC 4.6.3] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> file = open('a.txt').read()
    >>> file
    >>> file.split('\n')
    ['this is line 1', 'this is line 2', '']
    

    I'm on Linux, but I guess you just use \r\n on Windows and it would also work

    0 讨论(0)
  • 2020-12-03 07:16

    ✨ Splitting line in Python:

    Have you tried using str.splitlines() method?:

    • Python 2.X documentation here.
    • Python 3.X documentation here.

    From the docs:

    str.splitlines([keepends])

    Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

    For example:

    >>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
    ['Line 1', '', 'Line 3', 'Line 4']
    
    >>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
    ['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']
    

    0 讨论(0)
提交回复
热议问题