Reputation: 131
I have a string of the form
b'helloworld\r\n'
I would like to strip it of the \r\n and the the starting b. I tried using .rstrip("\n") but it crashes the system.
Upvotes: 0
Views: 17115
Reputation: 712
you can also decode the b-string (bytes-string), using .decode()
and then print()
it:
>>> yourBytesString = b'helloWorld\r\nnextLine\n'
>>> print(yourBytesString)
b'helloWorld\r\nnextLine\n'
>>> yourBytesString.decode()
'helloWorld\r\nnextLine\n'
>>> print(yourBytesString.decode())
helloWorld
nextLine
(adapted from this post.)
Upvotes: 1
Reputation: 1073
According to the Python docs, the b prefix means that your string is a byte string. Specifically:
A prefix of 'b' or 'B' is ignored in Python 2; it indicates that the literal should become a bytes literal in Python 3 (e.g. when code is automatically converted with 2to3). A 'u' or 'b' prefix may be followed by an 'r' prefix.
To convert this to a string without trailing newline and return, and to remove the byte prefix, you would use:
str(b'helloworld\r\n').rstrip('\r\n')
Upvotes: 5
Reputation: 24116
Try this:
b'helloworld\r\n'.strip() // leading + trailing
or
b'helloworld\r\n'.rstrip() // trailing only
Upvotes: 1
Reputation: 32189
There shouldn't be any problem. Just do:
your_string.rstrip()
rstrip()
without any parameters strips whitespaces, newlines and carriage returns.
Examples:
>>> s = 'helloworld\r\n'
>>> print s.rstrip()
helloworld
>>> s = 'helloworld \r\n'
>>> print s.rstrip()
helloworld
Upvotes: -1