w3resource

Python program to convert string to bytes using different Encodings

Python Bytes and Byte Arrays Data Type: Exercise-1 with Solution

Write a Python program to convert a given string to bytes using different encodings like UTF-8, UTF-16, ASCII etc.

Sample Solution:

Code:

def convert_to_bytes(input_string, encoding):
    try:
        encoded_bytes = input_string.encode(encoding)
        return encoded_bytes
    except Exception as e:
        print("Error:", e)
        return None

def main():
    try:
        input_string = "Python Exercises!"
        
        encodings = ["utf-8", "utf-16", "ascii"]
        for encoding in encodings:
            encoded_bytes = convert_to_bytes(input_string, encoding)
            if encoded_bytes is not None:
                print(f"Encoding: {encoding.upper()}")
                print("Original String:", input_string)
                print("Encoded Bytes:", encoded_bytes)
                print("Decoded String:", encoded_bytes.decode(encoding))
                print("=" * 40)
    except Exception as e:
        print("An error occurred:", e)

if __name__ == "__main__":
    main()

Output:

Encoding: UTF-8
Original String: Python Exercises!
Encoded Bytes: b'Python Exercises!'
Decoded String: Python Exercises!
Encoding: UTF-16
Original String: Python Exercises!
Encoded Bytes: b'\xff\xfeP\x00y\x00t\x00h\x00o\x00n\x00 \x00E\x00x\x00e\x00r\x00c\x00i\x00s\x00e\x00s\x00!\x00'
Decoded String: Python Exercises!
Encoding: ASCII
Original String: Python Exercises!
Encoded Bytes: b'Python Exercises!'
Decoded String: Python Exercises!

In the exercise above, the "convert_to_bytes()" function takes an input string and an encoding as arguments and encodes the string using the provided encoding. In the "main()" function, the input string is converted to different encodings (UTF-8, UTF-16, ASCII). It then decodes the encoded bytes back to strings and prints the results.

Flowchart:

Flowchart: Python program to convert string to bytes using different Encodings.

Previous: Python Extended Data Type Bytes and Byte Arrays Exercises Home.
Next: Python program for concatenating bytes objects

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/extended-data-types/python-extended-data-types-bytes-bytearrays-exercise-1.php