Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split bytes variable on newline

This is an unusual request, and I would appreciate some guidance! :)

I have a python variable, for simplicity we can call it 'output'

When I print output I get the following:

b"word1\nword2\nword3\n"

I would love it if I could print

word1
word2
word3
word4

I have tried to split the variable, and feed it to a for loop with zero success. I am happy to write the output to a file in the OS and use bash to resolve the issue as well.

Thanks!

like image 672
jeff_h Avatar asked Apr 07 '16 15:04

jeff_h


3 Answers

You'll need to do this (see the string.split function for more details)...

for word in output.decode('utf-8').split('\n'):
    print word

And you don't need to print word - you can do anything you want with it. This loop will iterate over every line in output.

like image 178
birdoftheday Avatar answered Nov 14 '22 21:11

birdoftheday


It sounds like you are using Python 3 and invoking the equivalent of

>>> print(b"foo\nbar\nbaz")
b'foo\nbar\nbaz'

This is str(bytes) in action: the (Unicode) string representation of a byte string. By decoding it first you get something that Python 3 will print more elegantly.

>>> print(b"foo\nbar\nbaz".decode('utf-8'))
foo
bar
baz
like image 24
joeforker Avatar answered Nov 14 '22 23:11

joeforker


To me it sounds like your string has escaped newlines. str.split won't help you here, nor str.splitlines. You need to decode the escapes:

>>> print s
word1\nword2\nwored3\n
>>> print s.decode('string-escape')
word1
word2
wored3
like image 40
wim Avatar answered Nov 14 '22 21:11

wim