Convert string to bytes Python | bytes & encode method

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.


convert a string to bytes encode

2. To convert bytes to a String.


convert bytes to a String decode

Examples:  Using bytes(enc)


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

More Examples:

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:-

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!


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

This site uses Akismet to reduce spam. Learn how your comment data is processed.