Sling Academy
Home/Python/Python: Converting a string to bytes and vice versa

Python: Converting a string to bytes and vice versa

Last updated: June 01, 2023

This concise example-based article shows you how to convert a string to bytes and vice versa in Python.

Converting a string to bytes

To turn a given string into bytes, you can use either the bytes() function or the str.encode() method. Both of them take a string as an input and return a bytes object that represents the string in a specified encoding.

Code example:

text = "Welcome to Sling Academy!"

# Convert 'text' to bytes using encode()
bytes_1 = text.encode('utf-8')
# Verify the type of 'bytes_1'
print(type(bytes_1))

# Convert 'text' to bytes using bytes()
bytes_2 = bytes(text, 'utf-8')
# Verify the type of 'bytes_2'
print(type(bytes_2))

Output:

<class 'bytes'>
<class 'bytes'>

The main difference between the two is that the bytes() function can convert various sources (not just strings) to bytes, while the str.encode() method specifically operates on strings.

Syntax of the bytes() function:

bytes(source, encoding, errors)

Where:

  • source: The source to be converted. It can be a string, an iterable of integers, or a buffer-like object.
  • encoding: The encoding to be used for the conversion. Defaults to ‘utf-8’.
  • errors: Specifies how encoding and decoding errors should be handled. Defaults to ‘strict’.

Syntax of the encode() method:

your_string.encode(encoding, errors)

Where:

  • encoding: The encoding to be used for the conversion. Defaults to utf-8.
  • errors: Specifies how encoding and decoding errors should be handled. Defaults to strict.

Converting bytes to a string

There are two options for bytes to string conversion.

Using the str() function

You can pass a bytes object to the str() function to get a string.

Example:

bytes_data = b"Welcome to Sling Academy!"

# bytes to string
string = str(bytes_data, 'utf-8')
# verify the type
print(f"The output is '{string}' and the type is {type(string)}")

Output:

The output is 'Welcome to Sling Academy!' and the type is <class 'str'>

The str() function can produce a string from an arbitrary object, not limited to a bytes object.

Using the decode() method

You can turn a bytes object into a string by calling the decode() method on it.

Example:

bytes_data = b"Welcome to Sling Academy!"

# byts to string
string = bytes_data.decode('utf-8')
# verify the type
print(type(string))

Output:

<class 'str'>

Unlike the str() function, the decode() method can only convert a bytes object into a string, not an arbitrary object. If you try to use the decode() method on an object that is not a bytes object, you will get an AttributeError.

Next Article: Python: How to Convert a String to Character Codes

Previous Article: Python: Remove non-alphanumeric characters from a string

Series: Working with Strings in Python

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types