Best way to convert string to bytes in Python 3

Posted in /  

Best way to convert string to bytes in Python 3

Vinay Khatri
Last updated on October 12, 2022

    In this tutorial, we will write the code for how to convert the String to a Byte in Python and vice versa. After reading this article, you will have a better understanding of how to deal with bytes data in Python and convert it into strings.

    A byte data object is a sequence of bytes (machine-readable data), and a string is a sequence of characters (human-readable data). To convert machine-readable Byte data into a human-readable string, we use decoding. And to convert the human-readable code to byte, we use decoding.

    Bytes and String Overview

    In Programming, everything is made up of 0 and 1, known as binary. The basic unit of binary is known as a bit, which means 0, and 1 are individually two bits. And a sequence of 8 bits is known as a byte (11001101).

    Computers or machines can only understand bytes, and humans interact with computers using readable data such as strings or text.

    In Python, we have various techniques to convert the Byte data into String and string data into bytes.

    So let’s get started,

    Convert string to bytes in Python

    Python has inbuilt function bytes() which can convert the given string into bytes. The bytes() method accepts the string and the encoding format such as utf-8 and ascii and convert the string into bytes.

    Example

    string = "Techgeekbuzz"
    
    # encode the string 
    
    encoded_1 = bytes(string, 'utf-8')
    
    encoded_2 = bytes(string, 'ascii')
    
    for i in encoded_1:
        print(i, end=" ")
    
    print()
    
    for i in encoded_2:
        print(i, end=" ")

    Output

    84 101 99 104 103 101 101 107 98 117 122 122 
    84 101 99 104 103 101 101 107 98 117 122 122 

    Convert the Bytes into String

    If we have a byte object in Python, we can apply the decode() method to the object to convert it into string data.

    Example

    byte = b"Let's go for \xf0\x9f\x8d\x95!"
    
    print(byte.decode())

    Output

    Leave a Comment on this Post

    0 Comments