摆脱回车和字符串中的新行

时间:2014-04-08 13:43:16

标签: python string

我有一个表格

的字符串
b'helloworld\r\n'

我想剥掉它的\ r \ n和起始b。我尝试使用.rstrip(“\ n”)但它崩溃了系统。

4 个答案:

答案 0 :(得分:4)

根据Python文档,b前缀表示您的字符串是一个字节字符串。具体做法是:

  

' b'的前缀或者' B'在Python 2中被忽略;它表明了   literal应该成为Python 3中的字节文字(例如,当代码是   自动转换为2to3)。 A' u'或者' b'前缀可能是   接着是一个' r'前缀。

要将此转换为不带尾随换行符并返回的字符串,并删除字节前缀,您可以使用:

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

答案 1 :(得分:1)

试试这个:

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

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

答案 2 :(得分:0)

您还可以使用.decode()然后使用print()对其b字符串(字节字符串)进行解码:

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

(根据post改编。)

答案 3 :(得分:-1)

不应该有任何问题。只是做:

your_string.rstrip()

没有任何参数的

rstrip()会删除空格,换行符和回车符。

示例:

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


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