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. https://en.wikipedia.org/wiki/Base64

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")
'dGVzdA=='
Enter fullscreen mode Exit fullscreen mode

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. https://docs.python.org/2/library/base64.html

In Python3 that has changed and it now accepts a "bytes-like-object."
https://docs.python.org/3/glossary.html#term-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")
b'test'
>>> base64.b64encode(bytes(s,"utf-8"))
b'dGVzdA=='

Enter fullscreen mode Exit fullscreen mode

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

Latest comments (2)

Collapse
 
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!

Collapse
 
tonetheman profile image
Tony Colston

Even better than mine! Good catch.