Today I learned strings can also be unpacked in Python.

Code snippet showing how to unpack strings.

String unpacking

I've written a couple of Pydon't articles about unpacking before, namely one about unpacking with starred assignments, and another one about deep (structural) unpacking.

Having said that, I have no idea why I was so surprised, earlier today, when I found out that strings can be unpacked in Python:

>>> a, b = "Hi"
>>> a
'H'
>>> b
'i'

In hindsight, I already possessed all the knowledge to arrive at this conclusion...

And yet, when I saw it in my face, it baffled me!

Now, whether or not this is a helpful thing... That's a whole different discussion!

But there you have it, something interesting about Python.

(Pssst, no one else is looking, check out this horror:

>>> first, *middle, last = "Hello, world!"
>>> first
'H'
>>> middle
['e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> last
'!'

Would you get fired if you wrote things like this in production?)

Here's the tweet from where I learnt this:

That's it for now! Stay tuned and I'll see you around!

Become a better Python 🐍 developer πŸš€

+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!

My book β€œPydon'ts” teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here πŸπŸš€.

Previous Post Next Post

Blog Comments powered by Disqus.