Python String Slicing
Table of Contents
In the last lesson, we learned about Python String Methods. Now letβs use slicing to take only the part of a string we need.
βοΈ Letβs Talk About Cutting Strings
We have a string. Maybe it is a long sentence. Maybe it is a word. And we want only a part of it.
Maybe we want the first three characters. Maybe we want everything except the last two. Maybe we want every second character.
That is what slicing is for.
Slicing lets us take a piece of a string. We specify where to start. Where to end. And how many steps to take. And Python gives us that part.
It works on strings, lists, and other sequences. But for now, letβs focus on strings.
π§ The Basic Idea of Python String Slicing
We use square brackets [ ] with a colon : inside.
text = "Hello, world!"print(text[0:5])Output
HelloLet me explain.
0is the start index. It means start from the first character.5is the end index. It means stop before index 5. So it includes indices 0, 1, 2, 3, 4.- The result is
"Hello".
Notice that the end index is not included. That is a common source of confusion. But it is consistent in Python.
π‘ Start and End in Python String Slicing
We can specify both start and end.
text = "Hello, world!"print(text[7:12])Output
worldBecause index 7 is w, index 8 is o, 9 is r, 10 is l, 11 is d. And 12 is not included.
We can also use negative indices.
print(text[-6:-1])Output
worldBecause -6 is the w (counting from the end), and -1 is !. But since end is exclusive, it stops before !. So we get world.
π§ͺ Leaving Out Start or End in Python Slicing
If we leave out the start, it starts from the beginning.
print(text[:5])Output
HelloIf we leave out the end, it goes to the end.
print(text[7:])Output
world!If we leave out both, we get the whole string.
print(text[:])Output
Hello, world!That is a common way to make a copy of a string. Though strings are immutable, so a copy is not usually needed. But for lists, it is useful.
π The Step in Python String Slicing
We can add a third number. That is the step.
print(text[::2])Output
Hlo ol!Let me explain. The step is 2. So it takes every second character. Starting from index 0, then 2, then 4, and so on.
We can also use a negative step to go backwards.
print(text[::-1])Output
!dlrow ,olleHThat reverses the string. Very handy.
Letβs see another example.
text = "abcdef"print(text[1:5:2])Output
bdStart at 1 (b), go up to 5 (not including), step by 2. So indices 1 and 3. That gives b and d.
π Python String Slicing: A Real-Life Example
Letβs say we have a date in the format βYYYY-MM-DDβ. And we want to extract the year, month, and day.
date = "2025-01-15"year = date[:4]month = date[5:7]day = date[8:]print(year, month, day)Output
2025 01 15That is clean and simple.
π Another Example β Reversing a String
word = "Python"reversed_word = word[::-1]print(reversed_word)Output
nohtyPThat is a common trick. And it works for any sequence.
π§ Slicing Does Not Change the Original String
Letβs remember, strings are immutable. Slicing creates a new string. It does not modify the original.
text = "Hello"part = text[1:3]print(part) # elprint(text) # HelloThe original text is still "Hello". The slice part is a new string "el".
β οΈ Common Mistakes with Python String Slicing
β Mistake 1: Forgetting That the End Index Is Exclusive
text = "Hello"print(text[0:4])Output
HellNot Hello. Because index 4 is not included. To get Hello, we need text[0:5] or just text[:].
So what do we do? We use the right end index, or leave it out.
π« Mistake 2: Using Out-of-Range Indices
Python is forgiving with slices. If we go out of range, it just goes as far as it can.
text = "Hello"print(text[0:100])Output
HelloNo error. It just stops at the end.
But if we use an index that is out of range for a single character, we get an error.
print(text[100]) # Error!Because that is indexing, not slicing.
π Mistake 3: Using a Step of Zero
print(text[::0])Output
ValueError: slice step cannot be zeroWe cannot have a step of zero. It makes no sense. So Python gives an error.
π Mistake 4: Confusing Slicing with Indexing
text = "Hello"print(text[1]) # eprint(text[1:2]) # eBoth give the same result. But one is indexing (single character) and one is slicing (a substring of length 1). They look similar but are different operations.
ποΈ A Real-Life Example with a List
Even though we are focusing on strings, slicing works on lists too.
numbers = [10, 20, 30, 40, 50]print(numbers[1:4])Output
[20, 30, 40]Same rules. Start at 1, go up to 4 (not including), so indices 1, 2, 3.
That is useful to know. But we will cover lists later.
β¨οΈ Slicing with Variables
We can use variables for the start, end, and step.
text = "Hello, world!"start = 7end = 12print(text[start:end])Output
worldThat is handy when the indices are calculated.
π§° Summary of Python Slicing Syntax
text[start:end:step]
startβ where to begin (inclusive). Default is 0.endβ where to stop (exclusive). Default is the end of the string.stepβ how many characters to skip. Default is 1.
We can omit any of them. But we must keep the colons in the right places.
For example:
text[:]β whole stringtext[2:]β from index 2 to endtext[:5]β from start to index 5 (not including)text[::2]β every second charactertext[::-1]β reversed string
Next, we will learn about Python String Formatting and insert values into clear, readable text.