Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
strings
bytes
convert

How to convert strings to bytes in Python

Educative Answers Team

A byte object is a sequence of bytes. These byte objects are machine-readable and can be directly stored on the disk. Strings, on the other hand, are in human-readable form and need to be encoded so that they can be stored on a disk.

There are several different types of encodings that can map text to the disk. The most popular ones are the​ ASCII and UTF-8 encoding techniques. ​

Convert strings to bytes

We can use the built-in Bytes class in Python to convert a string to bytes: simply pass the string as the first input of the constructor of the Bytes class and then pass the encoding as the second argument.

Printing the object shows a user-friendly textual representation, but the data contained in it is​ in bytes.

string = "Hello World"

# string with encoding 'utf-8'
arr = bytes(string, 'utf-8')
arr2 = bytes(string, 'ascii')

print(arr,'\n')

# actual bytes in the the string
for byte in arr:
    print(byte, end=' ')
print("\n")
for byte in arr2:
    print(byte, end=' ')

RELATED TAGS

python
strings
bytes
convert
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring