[英]Getting rid of Carriage return and new line in a string
我有一个表格字符串
b'helloworld\r\n'
我想去掉 \\r\\n 和起始 b。 我尝试使用 .rstrip("\\n") 但它使系统崩溃。
根据 Python 文档, b 前缀表示您的字符串是字节字符串。 具体来说:
'b' 或 'B' 前缀在 Python 2 中被忽略; 它表示文字在 Python 3 中应该变成字节文字(例如,当代码自动转换为 2to3 时)。 'u' 或 'b' 前缀后面可以跟一个 'r' 前缀。
要将其转换为不带换行符并返回的字符串,并删除字节前缀,您可以使用:
str(b'helloworld\r\n').rstrip('\r\n')
尝试这个:
b'helloworld\r\n'.strip() // leading + trailing
或者
b'helloworld\r\n'.rstrip() // trailing only
您还可以解码 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
(改编自这篇文章。)
应该没有什么问题。 做就是了:
your_string.rstrip()
不带任何参数的rstrip()
空格、换行符和回车符。
例子:
>>> s = 'helloworld\r\n'
>>> print s.rstrip()
helloworld
>>> s = 'helloworld \r\n'
>>> print s.rstrip()
helloworld
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.