Best way to convert string to bytes in Python 3

Posted in

Best way to convert string to bytes in Python 3
vinaykhatri

Vinay Khatri
Last updated on December 14, 2024

    In this tutorial, we will learn how to convert a String to a Byte in Python and vice versa. After reading this article, you will better understand 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 comprises 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 an 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 converts 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