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!
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
.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With