DEV Community

Tony Colston
Tony Colston

Posted on

strings in python2 and python3

I have written a lot of code in Python2. Not as much in Python3.

One thing I used Python for a lot is to quickly convert string values into base64 encoding.

In Python2 that looks something like this (using the repl)

Python 2.7.5 (default, Oct 30 2018, 23:45:53) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import base64
>>> base64.b64encode("test")

Sadly that quickly typed sequence does not work in Python3. Sigh.

The base64 module from Python2 used to take a string as an argument to the b64encode call.

In Python3 that has changed and it now accepts a "bytes-like-object."

And out of the box a string is not a bytes-like-object. So you have to convert it to use the string with b64encode.

Again using the Python repl now with Python3

Python 3.7.5 (default, Nov  6 2019, 11:03:32) 
[Clang 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> s="test"
>>> import base64
>>> bytes(s,"utf-8")
>>> base64.b64encode(bytes(s,"utf-8"))

Sadly more things to type with your fingers. But not fast and loose with the data types.

Discussion (3)

cipharius profile image
Valts Liepiņš

Luckily you can type byte string literals in Python3: base64.b64encode(b'test')
That should make it as neat and simple as in Python2!

tonetheman profile image
Tony Colston Author

Even better than mine! Good catch.

yujiri8 profile image
Ryan Westlund

I haven't benchmarked this or anything, but there's also str.encode as an alternative to the bytes constructor.