Converting Bytes to String in Python
Converting Bytes to String - Python |
To convert Bytes to String you can use a few methods: with str(), with decode and also with codecs. I'm going to show you how to decode Byte to Str with all of them.
People often try to convert Byte to String by wrong way.
b = bytes('This is string', encoding= 'utf-8')
string = str(b)
print(f'string is {type(string)}')
print(string)
string is <class 'str'>
b'This is string'
As you can see although the string is converted to String you'll still have "b'" in leading, it's because Python doesn't know you want to decode the bytes, so it gives representation of the byte string.
Here are the right ways to convert Byte to String:
Here are the right ways to convert Byte to String:
Decode Byte to String with Codecs
#decoding with codecs
import codecs
b = bytes('This is string', encoding= 'utf-8')
cod = codecs.decode(b, 'utf-8')
print(f'cod is {type(cod)}')
print(cod)
#output:
cod is <class 'str'>
This is string
Decode Byte to String with decode
#decoding with decode:
d= b.decode('utf-8')
print(f' d is {type(d)}')
print(d)
#output:
d is <class 'str'>
This is string
Decode Byte to String with str()
#decoding with str()
b = bytes('This is string', encoding= 'utf-8')
sd= str(b, 'utf-8')
print(f'sd is {type(sd)}')
print(sd)
#output:
sd is <class 'str'>
This is string
Read also:
- How to check if user user input is Empty
- Prevent fro crashing program when user enters no integer
- User Enters no integer - how to prevent program from crashing.
Comments
Post a Comment