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

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots