删除
来自 python 字符串

发布于 2024-08-11 05:55:19 字数 106 浏览 5 评论 0原文

当您在 Python 中通过 popen 运行某些内容时,结果来自缓冲区,并在每行末尾带有回车符 (13) 的 CR-LF 十进制值。如何从 Python 字符串中删除它?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

荭秂 2024-08-18 05:55:19

您只需将

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

所有出现的 CRNL 替换为 NL,这似乎就是您想要的。

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.

薄荷梦 2024-08-18 05:55:19
buffer = "<text from your subprocess here>\r\n"
no_cr = buffer.replace("\r\n", "\n")
buffer = "<text from your subprocess here>\r\n"
no_cr = buffer.replace("\r\n", "\n")
箹锭⒈辈孓 2024-08-18 05:55:19

如果它们位于字符串的末尾,我建议使用:

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

您也可以使用不带参数的 rstrip() ,这也会删除空格。

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.

土豪我们做朋友吧 2024-08-18 05:55:19

Replace('\r\n','\n') 应该可以工作,但有时却不能。多么奇怪啊。相反,你可以使用这个:

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

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
逐鹿 2024-08-18 05:55:19

实际上,您可以简单地执行以下操作:

s = s.strip()

这将删除字符串前导或尾随的所有无关空白,包括 CR 和 LF。

s = s.rstrip()

执行相同的操作,但仅尾随字符串。

即:

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...'

请参阅 http://docs.python.org/library/stdtypes.html 了解更多信息。

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.

盗梦空间 2024-08-18 05:55:19

您也可以执行 s = s.replace('\r', '')

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文