ylm February 2016

Python remove line breaks

I'm reading output from program like this

test_output = test_run.communicate(input=str.encode(input))[0]
output = test_output .decode('utf-8').strip()

and if program returns new line like this

>>> a
>>> b

it reads it like this(with repr())

>>> 'a\r\nb'

I tried removing line breaks with

output.replace(r"\r\n","")

but it's not working, if I print it like regular string it returns

>>> a
>>> b

and repr()

>>> 'a\r\nb'

How can I remove \r\n from my string?

Answers


Oin February 2016

Don't use a regexp, the regexp doesn't do what you think it does:

>>> 'a\r\nb'.replace('\r\n', '')
'ab'

i.e. just remove the r in replace(r'\r\n', '')

Post Status

Asked in February 2016
Viewed 1,498 times
Voted 11
Answered 1 times

Search




Leave an answer