The secret to becoming an effective Pythonista

Hey there,

As a Python coder, I enjoy going back to the basics from time to time.

I usually learn something new or interesting when I do it.

The other day I had a conversation about "string reversal"—like, how do you do this in Python: 

'TURBO' ---> 'OBRUT'

Well, if you're coming from a Java or C# background, you might be surprised to find that "str" objects in Python *do not* have a built-in ".reverse()" method. 

So this fails:

>>> 'TURBO'.reverse()
AttributeError: 'str' object has no attribute 'reverse'

But Python strings follow something called the "sequence protocol," meaning they can be treated like list objects under some circumstances.

And all sequences in Python support an interesting feature called "slicing." It uses the square-brackets indexing syntax you're already familiar with...

The interesting bit is that this syntax includes a special case, where slicing a sequence with "[::-1]" produces a *reversed copy* of the input sequence.

And so, because all Python strings are sequences, this is a quick and easy way to get a reversed copy of a string:

>>> 'TURBO'[::-1]
'OBRUT'

Mission accomplished.

Okay, now how do you like this solution?

It's short and sweet, that's for sure. But I've spoken with new Python developers who perceived it as odd and "arcane." 

I don't blame them—list slicing can be difficult to understand the first time you encounter its "quirky" and terse syntax.

When I’m reading Python code that makes use of slicing I often have to slow down and concentrate to "mentally parse" the statement, to make sure I understand exactly what’s going on...

My biggest gripe here is that the "[::-1]" slicing syntax doesn't communicate clearly that it creates a reversed copy of the original string.

So let's take a look at another option—

The fact that strings are sequences opened up a whole new box of tools for us. 

For example, Python sequences can be iterated over, accessing each element one by one.

And iteration is powered by another "protocol" that brings with it a treasure trove of generic functions and methods that can be applied to any sequence.

For example, the "reversed()" built-in function that allows you to create a reverse iterator for any sequence object.

You can then use this iterator to cycle through the elements in a string in reverse order, like so:

>>> for elem in reversed('TURBO'):
...     print(elem)
O
B
R
U
T

Now, using "reversed()" does not modify the original string—which wouldn't work anyway as strings are *immutable* in Python. (Meaning they're "frozen" after creation and can't be modified.)

What happens when you call "reversed()" is this:

You get a "view" of sorts into the existing string, which you can then use to access all elements in reverse order. This does not create a copy—

It's just a way to read the same elements in memory, but in a different order.

Now this is a powerful technique because it has a wide range of applications—not only can you use it to reverse lists, you can reverse *any* kind of sequence with it.

Learning just one more tiny tool opened up a slew of possibilities here!

Well okay, so far, all you've seen was how to *iterate* over the characters of a string in reversed order. Sometimes that's all you need to do.

But how can you use this technique to create a "reversed copy" of a Python string, just like in the slicing solution?

Here's how:

>>> ''.join(reversed('TURBO'))
'OBRUT'

This code snippet used another generic tool—the .join() method.

With it you can merge all of the characters resulting from the reversed iteration into a new string object (the reversed copy.)

I really like this reverse iterator approach for reversing strings in Python.

It communicates clearly what is going on. And even someone new to the language would intuitively understand that I’m creating a reversed copy of the original string.

While understanding how iterators work at a deeper level is helpful, it’s not absolutely necessary to use this technique. And I like code that's straightforward and readable.

Anyway, there's tons more to talk about—

More string reversal implementations (see how many you can come up with as a 20 minute challenge for yourself...)

Performance comparisons (which approach is faster?)

And so on...

But this email is getting a little long and I'm looking forward to lunch, so let's wrap things up.

Here's what I'd love for you to take away:

With one simple question—"How to reverse a string in Python?"—we've branched out into a number of interesting topics that are also valuable to your day to day work as coder.

Going back and reviewing the basics often does that.

Now it would be fairly easy for you to search for the right keywords in order to dig deeper and learn more.

And this is one of the best ways to grow your skills as a Pythonista in the long run. I highly recommend you give it a try.

If you want to explore other (awesome) Python features in a similar style, then check out my Python Tricks book.

Happy Pythoning!

— Dan Bader

Older messages

[PythonistaCafe] What's in PythonistaCafe for you?

Sunday, March 7, 2021

Hey there, A couple of years ago I'd become quite interested in martial arts. Hours upon hours of watching "The Karate Kid" growing up must've taken their toll on me... And so, I

[PythonistaCafe] Why PythonistaCafe exists

Saturday, March 6, 2021

Hey there, In one of my last emails I talked about how some online communities in the tech space devolve over time and turn into cesspools of negativity. This relates directly to how and why I started

KaraokeException("Pythonista Party Error")

Friday, March 5, 2021

Hey there, When I went to college to get my computer science degree some of my friends were really into "UltraStar Deluxe", an open-source karaoke game based on the PlayStation game "

[PythonistaCafe] Q&A

Friday, March 5, 2021

Hey there, At this point you should have a pretty good idea of what PythonistaCafe is about and what makes it special. In this email I want to answer some common questions that I get asked about the

[Python Dependency Pitfalls] The Iceberg

Thursday, March 4, 2021

Hey there, The other day I read this quote from a Python developer that made me stop and think: "As a noob with a little programming knowledge already, I've found setting up and installing

You Might Also Like

Check Out These Awesome Gifts!

Thursday, November 28, 2024

Let us help you check one thing off your to-do list with this guide to the best gifts for the holiday season. Make the holidays a little brighter with these great gift options. From health and wellness

🚀 Accelerate Your Growth As a Software Architect

Thursday, November 28, 2024

What students are saying about my courses More than 4300+ students already completed my courses. And they gave them a 4.9/5 ⭐ rating. I'd love to see your success story next on this wall of

🫵 Android Developer Previews Are Not For You — Virtual Reality Might Finally Be Socially Acceptable

Wednesday, November 27, 2024

Also: iPhone Camera vs. Digital SLR, and More! How-To Geek Logo November 27, 2024 Did You Know The band Radiohead was originally called "On a Friday"—the band was formed by high school

JSK Daily for Nov 27, 2024

Wednesday, November 27, 2024

JSK Daily for Nov 27, 2024 View this email in your browser A community curated daily e-mail of JavaScript news JavaScript Certification Black Friday Offer – Up to 54% Off! Certificates.dev, the trusted

Ranked | The World's Biggest Importers of Goods 🌎

Wednesday, November 27, 2024

As Trump tariffs are anticipated to disrupt global trade and push up prices for consumers, we show the world's biggest importers of goods. View Online | Subscribe | Download Our App >> 📱Book

Daily Coding Problem: Problem #1621 [Easy]

Wednesday, November 27, 2024

Daily Coding Problem Good morning! Here's your coding interview problem for today. This problem was asked by Google. A regular number in mathematics is defined as one which evenly divides some

Spyglass Dispatch: The Xitter Bail Out • OpenAI Tender • Grokking Grok • Smartphone Sales • Fischer Random Chess • Scott Bessent for Treasury

Wednesday, November 27, 2024

The Xitter Bail Out • OpenAI Tender • Grokking Grok • Smartphone Sales • Fischer Random Chess • Scott Bessent for Treasury The Spyglass Dispatch is a free newsletter sent out daily on weekdays. Feel

The Long Road Home: A Story of Loss, Learning, and Renaissance - PART 4

Wednesday, November 27, 2024

Top Tech Content sent at Noon! How the world collects web data Read this email in your browser How are you, @newsletterest1? 🪐 What's happening in tech today, November 27, 2024? The HackerNoon

Top Tech Deals 🏷️ PS5 Slim, 4K TVs, 10th Gen iPad, and More!

Wednesday, November 27, 2024

The Black Friday madness is here! How-To Geek Logo November 27, 2024 Top Tech Deals: PS5 Slim, 4K TVs, 10th Gen iPad, and More! The Black Friday madness is here! Black Friday sales are here, and we

The 165+ best Black Friday deals

Wednesday, November 27, 2024

Windows Super God Mode; Bluesky starter packs; Tech gifts under $100 -- ZDNET ZDNET Tech Today - US November 27, 2024 Black Friday 2024 live blog Best Black Friday deals 2024: 165+ sales live now