How to Convert String to Bytes in Python

We will introduce methods to convert string to bytes in Python 3.

  1. bytes constructor method
  2. str.encode method

bytes data type is a built-in type introduced from Python 3, and bytes in Python 2.x is actually the string type, therefore we don’t need to introduce this conversion in Python 2.x.

bytes constructor to convert string to bytes

bytes class constructor constructs an array of bytes from data like string.

bytes(string, encoding)

We need to specify the encoding argument, otherwise, it raises a TypeError.

>>> bytes("Test", encoding = "utf-8")
b'Test'
>>> bytes("Test")
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    bytes("Test")
TypeError: string argument without an encoding

str.encode construtor to convert string to bytes

str.encode(encoding=)

encode method of string class could also convert the string to bytes. It has one advantage compared to the above method, that is, you don’t need to specify the encoding if your intended encoding is utf-8.

>>> test = "Test"
>>> test.encode()
b'Test'
>>> test.encode(encoding="utf-8")
b'Test'

Related Articles - Python Bytes

  • How to Convert Bytes to Integers
  • How to Convert Int to Bytes in Python 2 and Python 3
  • How to Convert Bytes to String in Python 2 and Python 3
  • Related Articles - Python String

  • How to Convert Bytes to Integers
  • How to Convert Int to Bytes in Python 2 and Python 3
  • How to Convert Bytes to String in Python 2 and Python 3
  • How to Check a String Is Empty in a Pythonic Way
  • How to Remove Whitespace in a String
  • How to convert string to datetime
  • How to Convert String to Lowercase in Python 2 and 3
  • How to Check Whether a String Contains Substring in Python
  • How to Convert a List to String in Python
  • How to Convert String to Float or Int in Python
  • How to Read One File Line by Line to A List in Python
  • comments powered by Disqus