删除 来自 python 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1759619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove from python string
提问by directedition
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?
当您popen
在 Python 中运行某些内容时,结果来自缓冲区,每行末尾带有回车符 (13) 的 CR-LF 十进制值。如何从 Python 字符串中删除它?
回答by Benjamin Pollack
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.
用 NL 替换所有出现的 CRNL,这似乎是您想要的。
回答by John Millikin
buffer = "<text from your subprocess here>\r\n"
no_cr = buffer.replace("\r\n", "\n")
回答by cellcortex
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.
您也可以使用不带参数的 rstrip() 来删除空格。
回答by Chris Larson
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.
这将删除任何无关的空白,包括 CR 和 LF,字符串的前导或尾随。
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 now 包含“现在是一切顺利的时候......”
s = s.rstrip()
s now contains ' Now is the time for all good...'
s 现在包含“现在是一切顺利的时候了......”
See http://docs.python.org/library/stdtypes.htmlfor more.
有关更多信息,请参阅http://docs.python.org/library/stdtypes.html。
回答by YOU
You can do s = s.replace('\r', '')
too.
你也可以s = s.replace('\r', '')
。
回答by dumbass
replace('\r\n','\n') should work, but sometimes it just does not. How strange. Instead you can use this:
replace('\r\n','\n') 应该可以工作,但有时却不能。多奇怪。相反,您可以使用它:
lines = buffer.split('\r')
cleanbuffer = ''
for line in lines: cleanbuffer = cleanbuffer + line