Fix Python – How do I get rid of the b-prefix in a string in python?

Question

Asked By – Stan Shunpike

I have a string with a b-prefix:

b'I posted a new photo to Facebook'

I gather the b indicates it is a byte string.

How do I remove this b prefix? I tried:

b'I posted a new photo to Facebook'.encode("utf-8").decode("utf-8")

But this gives an error:

UnicodeEncodeError: 'charmap' codec can't encode characters in position 64-65: character maps to <undefined>

Now we will see solution for issue: How do I get rid of the b-prefix in a string in python?


Answer

decode the bytes to produce a str:

b = b'1234'
print(b.decode('utf-8'))  # '1234'

This question is answered By – hiro protagonist

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0