去除字符串中的回车和换行符

0 投票
4 回答
15377 浏览
提问于 2025-04-18 01:52

我有一个这样的字符串:

b'helloworld\r\n'

我想去掉字符串中的\r\n和开头的b。我试过用.rstrip("\n"),但这样会让系统崩溃。

4 个回答

-1

这应该没什么问题。你只需要这样做:

your_string.rstrip()

rstrip()这个方法不带任何参数时,会去掉字符串末尾的空格、换行符和回车符。

举个例子:

>>> s = 'helloworld\r\n'
>>> print s.rstrip()
helloworld


>>> s = 'helloworld             \r\n'
>>> print s.rstrip()
helloworld
1

你还可以把b字符串(字节字符串)解码,使用 .decode() 方法,然后用 print() 来输出它:

>>> yourBytesString = b'helloWorld\r\nnextLine\n'
>>> print(yourBytesString)
b'helloWorld\r\nnextLine\n'
>>> yourBytesString.decode()
'helloWorld\r\nnextLine\n'
>>> print(yourBytesString.decode())
helloWorld
nextLine

(这个内容改编自这个 帖子。)

1

试试这个:

b'helloworld\r\n'.strip() // leading + trailing

或者

b'helloworld\r\n'.rstrip() // trailing only
5

根据Python的文档,前面加个b的意思是你的字符串是一个字节字符串。具体来说:

在Python 2中,前面加上'b'或'B'的部分会被忽略;它表示在Python 3中,这个字面量应该变成字节字面量(比如,当代码通过2to3工具自动转换时)。而'u'或'b'前缀后面可以跟'r'前缀。

如果你想把这个字符串转换成没有换行符和返回符的普通字符串,并且去掉字节前缀,你可以使用:

str(b'helloworld\r\n').rstrip('\r\n')

撰写回答