How to convert bytes to string data type in Python 3?

Dung Do Tien Aug 16 2021 47

Hello Guys, I am a newbie in Python and I have some symbols in bytes data and I want to convert them to string symbols and display it to console.

byteValues = b"\xf0\x9f\x8d\x80 \xf0\x9f\x8d\x83 \xf0\x9f\x8d\x97"  
 
print(type(byteValues))  
print(byteValues)  
# I want to convert this bytes string to symbols

It's output

<class 'bytes'>
b'\xf0\x9f\x8d\x80 \xf0\x9f\x8d\x83 \xf0\x9f\x8d\x97'

It's not converted to symbols for me. So how can I convert bytes to string in Python?

Thank you many for any suggesstions.

Have 3 answer(s) found.
  • D

    Do Chuong Aug 16 2021

    You can use decode() method. This method is used to convert from one encoding scheme, in which the argument string is encoded to the desired encoding scheme. This works opposite to the encode.

    byteValues = b"\xf0\x9f\x8d\x80 \xf0\x9f\x8d\x83 \xf0\x9f\x8d\x97"  
     
    strDecode = byteValues.decode()  
    print(type(strDecode))  
    print(strDecode)  

    And output

    <class 'str'>
    🍀 🍃 🍗
    
  • M

    Mobile Legend Aug 16 2021

    You can use str() function. The str() function of Python returns the string version of the object.

    byteValues = b"\xf0\x9f\x8d\x80 \xf0\x9f\x8d\x83 \xf0\x9f\x8d\x97"  
     
    strDecode = str(byteValues, 'UTF-8') 
    print(type(strDecode))  
    print(strDecode)  

    And below is the output

    <class 'str'>
    🍀 🍃 🍗
    
  • W

    Weanich Sanchol Aug 16 2021

    I usually use codecs.decode() method to help me convert bytes to string in Python:

    import codecs
    byteValues = b"\xf0\x9f\x8d\x80 \xf0\x9f\x8d\x83 \xf0\x9f\x8d\x97"  
     
    strDecode = codecs.decode(byteValues) 
    print(type(strDecode))  
    print(strDecode)  

    I hope it is useful for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close