split byte string into lines

后端 未结 3 1286
离开以前
离开以前 2021-01-07 16:15

How can I split a byte string into a list of lines?

In python 2 I had:

rest = \"some\\nlines\"
for line in rest.split(\"\\n\"):
    print line


        
相关标签:
3条回答
  • 2021-01-07 16:27

    try this.. .

    rest = b"some\nlines"
    rest=rest.decode("utf-8")

    then you can do rest.split("\n")

    0 讨论(0)
  • 2021-01-07 16:41

    There is no reason to convert to string. Just give split bytes parameters. Split strings with strings, bytes with bytes.

    >>> a = b'asdf\nasdf'
    >>> a.split(b'\n')
    [b'asdf', b'asdf']
    
    0 讨论(0)
  • 2021-01-07 16:49

    Decode the bytes into unicode (str) and then use str.split:

    Python 3.2.3 (default, Oct 19 2012, 19:53:16) 
    [GCC 4.7.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> a = b'asdf\nasdf'
    >>> a.split('\n')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: Type str doesn't support the buffer API
    >>> a = a.decode()
    >>> a.split('\n')
    ['asdf', 'asdf']
    >>> 
    

    You can also split by b'\n', but I guess you have to work with strings not bytes anyway. So convert all your input data to str as soon as possible and work only with unicode in your code and convert it to bytes when needed for output as late as possible.

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