Python 2 vs Python 3: Base64 Encoding

Jan 12, 2019

Python 2.x

import base64bstr = '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 base64text = 'Hello'# 'Hello'type(text)# <class 'str'># convert str to bytesbstr = text.encode('utf-8')# b'Hello'type(bstr)# <class 'bytes'># convert bytes to base64b64str = base64.b64encode(bstr)# b'SGVsbG8='bstr = base64.b64decode(b64str)# b'Hello'# convert bytes to strtext = 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()

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.