Today I learned strings can also be unpacked in Python.
The Python 🐍 problem-solving bootcamp is starting soon. Join the second cohort now!
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:
Why does Mypy complain about unpacking a string? i.e.— Will McGugan (@willmcgugan) September 22, 2021
foo, bar, baz = "foo"
Not only that, but it complains it doesn't know what type foo, bar, and baz are.
*however* Mypy does like this:
foo, bar, baz = iter("foo")
And it correctly deduces the types of foo, bar, and baz. 🤔
That's it for now! Stay tuned and I'll see you around!
I write about Python every week. Join +16.000 others who are taking their Python 🐍 skills to the next level 🚀, one email at a time.