开发者

Remove 
 from python string

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


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.


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


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.


replace('\r\n','\n') should work, but sometimes it just does not. How strange. Instead you can use this:

lines = buffer.split('\r')
cleanbuffer = ''
for line in lines: cleanbuffer = cleanbuffer + line


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜