Slicing Strings
Basic Slicing
String slicing extracts substrings using the syntax: `string[start:stop:step]`
- **start**: inclusive beginning index (default 0)
- **stop**: exclusive ending index (default is the string’s length)
- **step**: increment (default 1)
Example
text = "Python Programming"
# Basic slices
first_word = text[0:6] # 'Python'
last_word = text[7:] # 'Programming'
every_second = text[::2] # 'Pto rgamn'
print(first_word)
print(last_word)
print(every_second)
Output
Python Programming Pto rgamn
Negative Indexing
Negative indices count backwards from the end of the string, with `-1` referring to the last character:
Example
text = "ABCDEFGH"
print(text[-1]) # 'H'
print(text[-3:]) # 'FGH'
print(text[-5:-2]) # 'DEF'
Output
H FGH DEF
Advanced Slicing
By combining slicing parameters, you can create powerful substring operations:
Example
text = "Python Programming"
# Reverse a string
reverse = text[::-1]
# Get every 3rd character from index 1 to 10
step_slice = text[1:10:3]
# Common patterns
last_three = text[-3:] # Last 3 characters
first_three = text[:3] # First 3 characters
print(reverse)
print(step_slice)
print(last_three)
print(first_three)
Output
gnimmargorP nohtyP yoh ing Pyt
ℹ️ Note: Slicing never raises an `IndexError`—out-of-range indices are handled gracefully.