Tips Tricks Tutorials

Convert str to bytes in python

The two data types, str and bytes, are mutually exclusive. One cannot legally combine them into one call. With the distinction between text and data, therefore, comes the need to convert between them.

>>> z = b”Hello World!”
>>> y = “Hello World!”
>>> type(z)
<class ‘bytes’>
>>> type(y)
<class ’str’>

To convert from str to bytes, use str.encode().

>>> b = str.encode(y)
>>> type(b) <class ‘bytes’> >>> b b’Hello World!’

To convert from bytes to str, use bytes.decode().

>>> a = bytes.decode(z)
>>> type(a)
<class ’str’>
>>> a
‘Hello World!’

For how to accomplish the same thing with Python 3.0’s built-in functions, see “Converting str to bytes via Functions“, next in this series.

Note: Having a better understanding of text and data facilitates good programming. To fill out your understanding of programming under Python 3.0, be sure to check out

Alternatively, one can use the functions for these data types: byte(string, encoding=…) and str(bytestring, encoding=…).

>>> e = bytes(a, encoding=’utf8′)
>>> type(e)
<class ‘bytes’>
>>> f = str(b, encoding=’utf8′)
>>> type(f)
<class ’str’>

You can leave a response, or trackback from your own site.

One Response to “Convert str to bytes in python”

  1. René says:

    I\’m getting different stuff on my english windows xp, python 2.6 box:

    >>> z = b\"Hello world!\"
    >>> type(z)
    <type \’str\’>
    >>> bytes
    <type \’str\’>
    >>>

    seems bytes is just an alias for str.

    Anyway, thanks for the info!

Leave a Reply

New Free AT&T Cell Phones for Sale | Thanks to Credit Card Offers, Bank Reviews & Ratings and Cheap Loan