Python 2 vs Python 3: Base64 Encoding

January 12, 2019

Python 2.x

import base64

bstr = 'Hello'

type(text)
# <type 'str'>

b64str = base64.b64encode(bstr)
# 'SGVsbG8='


bstr = base64.b64decode(b64str)
# 'Hello'

NOTE: Python 2.x base64.b64encode accept str input.

Python 3.x

import base64

text = 'Hello'
# 'Hello'

type(text)
# <class 'str'>

# convert str to bytes
bstr = text.encode('utf-8')
# b'Hello'

type(bstr)
# <class 'bytes'>

# convert bytes to base64
b64str = base64.b64encode(bstr)
# b'SGVsbG8='

bstr = base64.b64decode(b64str)
# b'Hello'

# convert bytes to str
text = bstr.decode('utf-8')
#'Hello'

NOTE: Python 3.x base64.b64encode accept bytes input.

In Python 3, 'str' is unicode string and b'bytes' is byte string. In Python 2, 'str' is byte string and u'unicde' is unicode string. Refer to Python 2 vs Python 3: Byte, Str and Unicode.

Convert str to base64 string in one line.

text = '...'
base64.b64encode(text.encode()).decode()
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.