Remove
from python string

£可爱£侵袭症+ 提交于 2019-12-22 10:28:59

问题


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?


回答1:


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.




回答2:


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



回答3:


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.




回答4:


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.




回答5:


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




回答6:


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


来源:https://stackoverflow.com/questions/1759619/remove-13-from-python-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!