DEV Community

Tony Colston
Tony Colston

Posted on

1 2

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top 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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay