tags:

views:

324

answers:

5

When you run something through popen in Python, the results come in from the buffer with the CR-LF decimal value of a carriage return (13) at the end of each line. How do you remove this from a Python string?

+2  A: 

You can simply do

s = s.replace('\r\n', '\n')

to replace all occurrences of CRNL with just NL, which seems to be what you want.

Benjamin Pollack
+2  A: 
buffer = "<text from your subprocess here>\r\n"
no_cr = buffer.replace("\r\n", "\n")
John Millikin
+1  A: 

If they are at the end of the string(s), I would suggest to use:

buffer = "<text from your subprocess here>\r\n"
no_cr = buffer.rstrip("\r\n")

You can also use rstrip() without parameters which will remove whitespace as well.

krow
A: 

Actually, you can simply do the following:

s = s.strip()

This will remove any extraneous whitespace, including CR and LFs, leading or trailing the string.

s = s.rstrip()

Does the same, but only trailing the string.

That is:

s = '  Now is the time for all good...  \t\n\r   "
s = s.strip()

s now contains 'Now is the time for all good...'

s = s.rstrip()

s now contains ' Now is the time for all good...'

See http://docs.python.org/library/stdtypes.html for more.

Chris Larson
A: 

You can do s = s.replace('\r', '') too.

S.Mark