Skip to content

Convert string to bytes Python | bytes & encode method

  • by

To convert string to bytes in Python, you have to use a bytes() method or encode() function. A bytes() method returns a bytes object which is immutable (value can’t be modified). If you want a mutable value then use bytearray() method.

String to bytes is more popular these days due to the fact that for handling files or Machine Learning ( Pickle File ).

Methods to convert string to bytes

  • bytes(str, enc)
  • encode(enc)

Examples:  Using encode(enc)

1. To convert a string to bytes.

str = "Hello"  # string

print(str, type(str))

data = str.encode()  # bytes

print(data,type(data))

Output:

convert a string to bytes encode

2. To convert bytes to a String.

byt = b"Hello"  # bytes

print(byt, type(byt))

data = byt.decode()  # string

print(data,type(data))

Output:

convert bytes to a String decode

Examples:  Using bytes(enc)

msg = "Python is best"

# printing original string  
print("The original string : " + str(msg))

# Using bytes(str, enc) 
# convert string to byte  
res = bytes(msg, 'utf-8')

# print result 
print("The byte converted string is  : " + str(res) + ", type : " + str(type(res))) 

Output:

The original string: Python is best
The byte converted string is: b’Python is best’, type :

More Examples:

my_str = "hello world"
my_str_as_bytes = str.encode(my_str)
type(my_str_as_bytes) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
type(my_decoded_str) # ensure it is string representation

Q: The Best way to convert string to bytes in Python 3?

Answer:  The first parameter to encode defaults to 'utf-8' ever since Python 3.0. Thus the absolutely best way is:-

b = mystring.encode()

This will also be faster because the default argument results not in the string "utf-8" in the C code, but NULL, which is much faster to check!

Source: https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Examples Convert method used bytes() and encode() Python are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading