Reputation: 853
First, I have bytes
class object "myst". I then convert it to a str
class using str()
, and remove the whitespace using the strip()
method. The problem is that the whitespace "\r\n" is not removed.
>>> myteststring=b'asdf\r\n'
>>> str(myteststring)
"b'asdf\\r\\n'"
>>> str(myteststring).strip()
"b'asdf\\r\\n'"
But, using the strip()
method on a byte
class works properly.
>>> byteclass=b'asdf\r\n'
>>> byteclass.strip()
b'asdf'
What's wrong here?
I think when I use str()
, the resulting string includes double back slash \\
. This is may be root of my problem.
>>> myteststring
b'asdf\r\n'
>>> str(myteststring)
"b'asdf\\r\\n'" # << this is problem ??
Upvotes: 0
Views: 505
Reputation: 106543
When passed a bytes
object without an encoding
argument, the str
function would simply call the repr
function to return the string representation of the given bytes
object, which is why str(myteststring)
returns "b'asdf\\r\\n'"
, with \r\n
escaped with additional backslashes.
You can properly convert a bytes
object to a string by passing to the str
function an encoding
argument instead:
>>> myteststring=b'asdf\r\n'
>>> str(myteststring, encoding='utf-8')
'asdf\r\n'
>>> str(myteststring, encoding='utf-8').strip()
'asdf'
Upvotes: 5