How to encode string to bytes?

To encode a string to bytes in Python, you can use the encode() method of the string. Here’s a simple example:

# Example string
input_string = "Hello, World!"

# Encoding the string to bytes using UTF-8
encoded_bytes = input_string.encode('utf-8')

print(encoded_bytes)  # Output: b'Hello, World!'

In this example, the string "Hello, World!" is encoded to bytes using the UTF-8 encoding scheme. You can replace 'utf-8' with other encoding schemes like 'ascii', 'utf-16', etc., depending on your requirements.

0 Comments

no data
Be the first to share your comment!