1. Home
  2. Computing & Technology
  3. Python

A Guide to Text vs Data in Python 3.0

From , former About.com Guide

3 of 4

Converting str to bytes via Methods

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 "Transitioning from 2.x to 3.0".

Explore Python
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.