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()