Skip to main content

Command Palette

Search for a command to run...

Breaking Down Python’s String Reversal

Updated
1 min read

I’ve known for a while that reversing a string in Python is "text"[::-1]. However, it’s only now that I’ve truly understood how that works. Here’s what I learned today!

Breaking Down the Syntax

String slicing in Python uses the [start:stop:step] syntax. Here’s what each part does when reversing a string:

  • Start (:): Specifies the starting index. It defaults to the beginning of the string.

  • Stop (:): Specifies the stopping index. It defaults to the end of the string.

  • Step (-1): Determines the step size. A negative step, such as -1, means take one step backwards.

Let’s take the string a1b2c3 . To reverse it, we’d use:

>>> "a1b2c3"[::-1]
'3c2b1a'

The fun part is you can use the step size to extract just the numbers or just the letters from this string. Let’s explore:

Extract every second element (letters only):

>>> "a1b2c3"[::2] 
'abc'

Extract every second element starting from index 1 (numbers only):

>>> "a1b2c3"[1::2] 
'123'

We can use negative step sizes to extract specific parts of the string in reverse order.

Reverse and grab every second character (numbers):

>>> "a1b2c3"[::-2] 
'321'

Reverse and grab every second character starting from the second-to-last position (letters):

>>> "a1b2c3"[-2::-2] 
'cba'

More from this blog

C

Chuma Kabaghe

12 posts

Breaking Down Python’s String Reversal