🎓 A1Learner
🔍
0 of 116 lessons completed

Python String Slicing

A slice is a piece copied from a string, using two indexes and a colon. The slice stops before its second index.

Cut out a piece

This slice starts at index 1. It stops before index 4.

text = "Python"
print(text[1:4])

Leave an end open

A blank start means index 0. A blank stop means the end.

text = "Python"
print(text[:3])
print(text[2:])

Negative slice bounds

Negative bounds count back from the end, just like indexes.

text = "Python"
print(text[-3:])
print(text[:-2])

Take a step

Step 2 takes every second character.

text = "Python"
print(text[::2])

Reverse a string

Step -1 walks backwards through the string.

text = "Python"
print(text[::-1])

Wide bounds are safe

This stop is far past the end. Python gives the whole string, with no error.

text = "Python"
print(text[0:100])

Example

date = "2026-10-22"
year = date[:4]
month = date[5:7]
day = date[8:]
print(year)
print(month)
print(day)

Key points

  • Slice: a piece cut from a string, using two indexes and a colon
  • The slice starts at the first index
  • The slice stops before the second index
  • Leave an end blank to use the start or the finish
  • Add a step as a third number to skip characters
  • One index picks a single character.

In this example, date holds the text 2026-10-22. date[:4] takes the first four characters, the year. The dashes sit at indexes 4 and 7, so the code skips them. date[5:7] takes the month, 10. date[8:] takes everything from index 8, the day. The three print lines show each part on its own line.

Note

A slice never raises an error for wide bounds.

Python just gives you what exists, even if that is nothing.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does "hello"[1:3] give?