Python String to bytes, bytes to String With Examples

Python String to bytes

Python String to bytes conversion can be done in two ways:

  1. Using bytes() constructor and passing string and encoding as argument.
  2. Using encode() method on string object.

Python bytes to String

We can convert bytes to String using bytes class decode() instance method.

Let’s look at examples of converting a string to bytes and then bytes to string in a python program.

Output:

Best way to convert a string to bytes

Both the ways to convert a string to bytes are perfectly fine. String encode() and decode() method provides symmetry whereas bytes() constructor is more object-oriented and readable approach. You can choose any of them based on your preference.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: str.encode() api doc, bytes.decode() api doc

By admin

Leave a Reply

%d bloggers like this: