8) Text and Strings Lesson

String Slicing in Python

10 min to complete · By Martin Breuss

The syntax you previously used for indexing a string and picking out a specific character can also be used to pick out whole substrings from a Python string. Doing so is called string slicing and can get you some delicious new pieces of your original strings.

String Slicing Syntax

The syntax for picking substrings from an existing string closely resembles the syntax used for string indexing that you learned about in the previous lesson. Assume that you're playing a word game, and you need to pick out as many words as possible from a given string. Start off with a feathery word:

s = "plumage"

You might quickly find two words hidden within this word, but how can you pick them out of there?

Square Bracket Notation

To extract the word plum from plumage, you'd need to slice the string like so:

s[0:4]  # plum

Time to discuss this syntax within the square brackets in a little more detail:

  • Start: You pass in the index of the first character that you want to be part of your resulting word.
  • Separator: You place a colon (:) as a separator.
  • End: You add the index of the character one after the last one that you want to be part of your new string.

While the start and the separator might make intuitive sense, the value for end might seem a little confusing. If you want, you can note it down to Python's eccentric way of counting ¯\_(ツ)_/¯ but you can read about why this is the way it's implemented a bit further down.

Colorful illustration of a light bulb

Note: When you slice a string in Python, the start character is always included, and the end character is always excluded.

With this in mind, spin up your text editor or your Python REPL and play around some more with string slicing.

Python Slicing Shortcuts

Python provides two convenience shortcuts for string slicing. Namely, you don't need to specify the start or end index if you want to slice all the way to the beginning or the end of your string. Instead, you can simply leave out that number but still write the separator colon:

s = "plumage"

s[:4]  # plum
s[4:]  # age

Omitting any of the start or end indices in your string slice tells Python to go all the way.

Colorful illustration of a light bulb

Info: Because of this syntax, you can create an exact copy of a string with the syntax s[:]. Give it a try!

Similar to using the above-mentioned syntax to copy a string, there is a shorthand way that you can use to reverse a string in Python. To successfully achieve this, you need to know one more interesting feature of Python string slicing.

String Slicing Example

  • Extract the word "age" from the given word "plumage"
  • Can you accomplish this task using negative indexing?
  • Can you find yet another valid English word within the word plumage?

After you have extracted both of the substrings, you can reconsider why Python doesn't include the end character when slicing. The reason for this is that it ensures that with a defined index i (for example that could be 4), everything up to that index plus everything from that index will always create the complete string:

s = "plumage"

s[0:4]  # plum
s[4:7]  # age
s[0:4] + s[4:7]  # plumage

As you might see, if both the start and end were inclusive, then this could lead to unexpected results. (In this case, it would create a purple wizard that might drown the world in sticky fruit juice...)

However, you may have noticed something else that's strange here. In order to go all the way to the end of the string, you need to type in an index number that isn't part of the string anymore.

This makes sense since you want to include the last character, and for that, you need to give the index of the next character after the last one you want to include. Still, it seems a little unintuitive, and Python has a better way of handling this situation.

Python Slicing with Strides

Additionally to defining a window from where the substring should be taken, you can also define a stride. In string slicing, the stride tells Python the size of steps to take when considering the slice you defined.

The default stride is 1, which means that Python will consider every character in the substring range. Since that is the default, you don't even need to specify it. Nevertheless, you can still do it:

s = "plumage"
s[0:4:1]  # plum

Add a Step

The syntax for specifying the step of your slice is done by adding another colon (:) followed by another integer. The final integer stands for the size of the step. Here is what happens when you change the step:

s = "plumage"
s[0:4:2]  # pu

Compare the two outputs and think about what has happened here. Spin up a Python REPL, play around with this syntax, and make sure that you understand how it works. When you think you got a hang of it, get ready for a challenge:

Practice

  • Reverse a string in only one line of code, combining your knowledge of indexing, slicing, and strides.

When you have found the solution to reverse a string in one line of code, feel free to go ahead and look on the internet to see how some other programming languages handle this task. Most of the examples are a lot more complicated than in Python. This elegance and user-friendliness of Python's syntax are some of the reasons why it is a great language to pick up.

Colorful illustration of a light bulb

Additional Resources

Summary: String Slicing in Python

  • Python string slicing is when you extract a sub-string from it's parent string
  • Syntax: Inside of square brackets, use an inclusive start index position separated from an exclusive end index position by a colon
  • Shortcuts: Omit the start or the end index to slice all the way to the start or end of the string, respectively
  • Stride: The size of steps that Python takes over your slice is set with a third number separated by a colon
  • Reverse: String slicing, combined with strides, gives you a shorthand way to reverse a string