Python String Slicing
Table of Contents + −
In the last lesson you learned String Methods. Those let you change a whole string at once. But sometimes you do not want the whole thing. You only want a piece of it. Maybe the first three letters. Maybe the last four. Maybe every second character. That is where slicing comes in.
🤔 Why Slicing?
Picture this. You have some text and you only need a part of it. Doing that by hand is messy. You would loop over the characters, count positions, build up a new string, and hope you did not miss one. It is easy to get wrong.
Here are the kinds of jobs that come up all the time:
- You have a file name like
"report.pdf"and you want just the"pdf"part. - You have a card number and you want to hide everything except the last four digits.
- You have an email and you want the part after the
@. - You have a word and you want to read it backward.
Slicing is Python’s built-in way to pull out any part of a string. You just say where to start and where to stop, and Python hands you that piece. No loop, no counting by hand. So let’s see how it works.
🧩 Strings Are Numbered
Here is the key idea. Every character in a string sits at a position. Those positions are numbered. And Python starts counting at 0, not 1.
So the first character is at position 0. The second is at position 1. And so on. This is called the index of the character.
Take the word "PYTHON". Let’s lay it out so you can see each letter and the number sitting under it.
P Y T H O N 0 1 2 3 4 5 <- index from the start-6 -5 -4 -3 -2 -1 <- index from the endThe same idea in a table, so it is easy to scan:
| Character | P | Y | T | H | O | N |
|---|---|---|---|---|---|---|
| Index from start | 0 | 1 | 2 | 3 | 4 | 5 |
| Index from end | -6 | -5 | -4 | -3 | -2 | -1 |
So the P is at index 0. The N is at index 5. Counting from 0 surprises a lot of people at first. So keep it in mind, right? The first thing is at zero.
🔢 Grabbing One Character
To read a single character, put its index in square brackets after the string.
This grabs the first and the third letters of the word:
word = "PYTHON"
print(word[0])print(word[2])Output
PTLet’s walk through it:
word[0]givesP, notY. The first character lives at0.word[2]skips pastPandYto land onT. So index2is the third letter, because we started counting at zero.
⬅️ Counting From the End
What if you want the last character but you do not know how long the string is? Counting from the front would mean measuring the length first. That is annoying.
Negative indexing fixes that. A minus sign counts backward from the end. So -1 is the last character. -2 is the second to last. And so on.
This reads the last letter and the second-to-last letter:
word = "PYTHON"
print(word[-1])print(word[-2])Output
NOSee how -1 lands on N, the very last letter? You did not need to know the word was six letters long. That is the whole point. There is no -0, so the end starts at -1.
✂️ Slicing a Range
Reading one character is useful. But the real power is grabbing a whole range at once. The shape is text[start:stop]. You give a start position and a stop position, separated by a colon.
There is one rule you must remember. Stop is not included. Python stops just before it. So text[0:3] gives you the characters at 0, 1, and 2. It does not give you 3.
This pulls out the first three letters:
word = "PYTHON"
print(word[0:3])Output
PYTIt grabbed indexes 0, 1, and 2. The character at index 3 (H) was left out.
Now, why does the count work out so cleanly? Here is the simple way to think about it. The length of the slice is just stop minus start. So 3 - 0 is 3 characters. That is why word[0:3] gives you exactly three letters. Once you see that, off-by-one mistakes mostly go away.
You can also leave a side empty. If you skip the start, Python begins at the beginning. If you skip the stop, it goes all the way to the end.
This shows both shortcuts:
word = "PYTHON"
print(word[:3])print(word[3:])Output
PYTHONSo here is what each one means:
word[:3]means “from the start up to index 3”. Same asword[0:3], just shorter.word[3:]means “from index 3 to the end”. Same as going right up to the last character.- Together they split the word neatly into two halves with no gap and no overlap.
And there is one more handy shortcut. word[:] leaves out both sides. That means “from the start to the end”, so you get the whole string back as a brand-new copy.
This makes a full copy of the word:
word = "PYTHON"
copy = word[:]print(copy)Output
PYTHONIt looks the same, but copy is a separate string. We will see why that matters a bit later.
🔚 Grabbing the Last Few
Negative numbers work inside a slice too. This is the clean way to grab the last few characters of something. And it works without knowing the length.
Say you have a file name and want just the extension:
file_name = "report.pdf"
print(file_name[-3:])Output
pdffile_name[-3:] means “start three characters from the end, then go to the end”. You get pdf no matter how long the file name is.
There is a partner trick too. text[:-1] means “from the start, but stop just before the last character”. So it gives you everything except the last one. Remember, stop is not included, so a stop of -1 leaves out that final character.
This drops the last character of the word:
word = "PYTHON"
print(word[:-1])Output
PYTHOThe N is gone. This is handy when you want to remove a trailing character, like a stray comma or a newline at the end of a line.
👣 Adding a Step
There is a third number you can add: text[start:stop:step]. The step says how many characters to jump each time. By default the step is 1, so it walks one character at a time. Give it 2 and it skips every other one.
This takes every second character of the word:
word = "PYTHON"
print(word[::2])Output
PTOBoth sides are empty, so it runs across the whole word. The 2 makes it take P, skip Y, take T, skip H, take O, skip N. You are left with PTO.
🔄 Reversing a String
Here is a neat trick that uses a negative step. A step of -1 walks the string backward. That reverses it.
This flips the word end to end:
word = "PYTHON"
print(word[::-1])Output
NOHTYPLet’s break down why this works:
- The empty start and stop mean “the whole string”.
- The
-1step means “move backward one character at a time”. - So Python starts at the last letter
Nand walks back to the first letterP.
This [::-1] pattern is the common way people reverse a string in Python. Other Python developers will know it on sight. So it is worth remembering.
🌍 Real Examples
Slicing really clicks once you use it on real text. So let’s run through a few jobs you will actually do.
This pulls a file’s extension and an email’s domain:
file_name = "photo.png"email = "alex@gmail.com"
extension = file_name[-3:]domain = email[email.index("@") + 1:]
print(extension)print(domain)Output
pnggmail.comHere is what is happening:
file_name[-3:]grabs the last three characters, so you getpng.- For the email,
email.index("@")finds where the@sits. We add1to start just after it, then slice to the end. So we get everything after the@, which is the domain.
Now a common one in apps that show payment info. You want to hide a card number but still show the last four digits.
This masks a card number and keeps only the last four:
card = "1234567812345678"
last_four = card[-4:]masked = "*" * (len(card) - 4) + last_four
print(masked)Output
************5678Let’s read it line by line:
card[-4:]takes the last four digits,5678.len(card) - 4counts how many digits to hide. We make that many*characters with"*" * n.- Then we join the stars and the last four together. So the customer sees their last four and nothing else.
Slicing also helps you build initials. Take the first letter of two words.
This makes initials from a first name and last name:
first = "Riya"last = "Sharma"
initials = first[0] + last[0]
print(initials)Output
RSfirst[0] is R and last[0] is S. We add them together to get RS. Simple, and it does not care how long the names are.
🛡️ Slices Never Go Out of Range
Here is a really friendly thing about slicing. A slice never crashes, even if your numbers go past the end of the string.
If you ask for a single index that does not exist, Python stops you with an error. But a slice just gives you what it can and stops at the end.
This shows both, the safe slice and the index that fails:
word = "PYTHON"
print(word[0:100]) # asks way past the endprint(word[20]) # this line raises an errorOutput
PYTHONTraceback (most recent call last): File "main.py", line 4, in <module> print(word[20])IndexError: string index out of rangeSo look at the difference:
word[0:100]does not break. The word is only six letters, so Python just stops at the end and gives youPYTHON.word[20]is a single index, and there is no character at position20. So Python raises anIndexErrorand stops the program.
This is why slicing feels safe. You can ask for text[-4:] to get the last four characters even if the string is only two characters long, and nothing crashes. You just get whatever is there.
📌 Strings Don’t Change
One more important thing. Strings in Python are immutable. That means a string cannot be changed after you make it. So when you slice a string, Python does not touch the original. It builds a brand-new string for you and leaves the old one exactly as it was.
This slices a string and then checks the original:
word = "PYTHON"
piece = word[0:3]
print(piece)print(word)Output
PYTPYTHONSee? piece is the new PYT, but word is still the full PYTHON. The slice gave you a fresh string and did not change the source. So you can slice the same string as many times as you like without worrying about wrecking it.
⚠️ Common Mistakes
A few things trip people up when they are starting with slicing:
- Thinking the first character is at index
1. It is at0. Counting starts from zero, so the first letter sits at zero. - Expecting the stop index to be included. It is not.
word[0:3]stops just before index3, so you get three letters, not four. - Mixing up which number is start and which is stop. The first is where you begin, the second is where you stop. So
word[2:5]starts at2and stops before5. - Mixing up index and slice.
word[2]gives one character, the letterT.word[2:3]gives a one-character string that also readsT, but it came from a range.
Here is the start-at-zero trap in code:
word = "PYTHON"
# ❌ Avoid: thinking index 1 is the first letterprint(word[1]) # this is Y, not P
# ✅ Good: the first letter is at index 0print(word[0]) # this is POutput
YPAnd here is the off-by-one trap on stop:
word = "PYTHON"
# ❌ Avoid: expecting word[0:3] to include index 3print(word[0:3]) # this is PYT, the H is left out
# ✅ Good: go to 4 if you actually want the H includedprint(word[0:4]) # this is PYTHOutput
PYTPYTH✅ Best Practices
- Use
[:n]and[n:]instead of writing out[0:n]when one side is the start or the end. It reads cleaner. - Reach for negative indexes when you want something from the end.
text[-1]is clearer than counting the length yourself. - Remember
[::-1]for reversing. It is the pattern other Python developers will recognize right away. - Use
stop - startin your head to predict how many characters you will get. It kills off-by-one mistakes. - When a slice surprises you, picture the index table and remember that stop is not included.
🧩 What You’ve Learned
✅ Every character in a string has an index, and counting starts at 0.
✅ Negative indexes count from the end, so -1 is the last character.
✅ A slice is text[start:stop:step], and the stop position is not included.
✅ You can leave the start or stop empty to mean “the beginning” or “the end”, and [:] makes a full copy.
✅ A step like [::2] skips characters, and [::-1] reverses the whole string.
✅ Slices never go out of range, and because strings are immutable, a slice returns a new string and leaves the original alone.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
For the string word = "PYTHON", what does word[0] return?
Why: Indexing starts at 0, so word[0] is the first character, P.
- 2
What does the slice word[0:3] give for "PYTHON"?
Why: The stop index is not included, so you get characters at 0, 1, and 2: PYT.
- 3
For text = "report.pdf", what does text[-3:] return?
Why: A start of -3 begins three characters from the end and runs to the end, giving pdf.
- 4
What happens when you run word[0:100] on the string "PYTHON"?
Why: Slices never go out of range. Python just stops at the end of the string and returns PYTHON, no error.
🚀 What’s Next?
Now that you can pull pieces out of a string, the next step is putting values neatly into one. Up next you will learn how to build clean, readable text with formatting.