Slicing Strings
Learn Python string slicing with syntax, index diagrams, step values, negative indices, and practical real-world examples.
Python String Slicing
String slicing lets you extract a substring from a larger string by specifying where to start, where to stop, and how many characters to skip at a time. It is one of the most common string operations in Python and is used everywhere from parsing file names to reversing words.
This chapter covers:
- The
[start:stop:step]syntax and how indices map to characters - Omitting start or stop (slicing from the beginning or to the end)
- Negative indices (counting from the right)
- The step parameter (skip characters, reverse a string)
- Common gotchas: out-of-range indices, empty slices
- Practical examples you can run immediately
If you are new to strings in Python, read the Python Strings chapter first — it explains how strings are created and indexed.
How String Indices Work
Every character in a Python string has two indices: a positive one (counting from the left, starting at 0) and a negative one (counting from the right, starting at -1).
For the string "Hello, World!":
H e l l o , W o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12 ← positive
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 ← negativeThe full slicing syntax is:
string[start:stop:step]start— index of the first character to include (default:0)stop— index of the first character to exclude (default: end of string)step— how many characters to advance each time (default:1)
The stop index is exclusive — the character at stop is never included in the result.
Basic String Slicing
Provide a start and stop index separated by a colon to extract the characters between them.
my_string[0:3] returns characters at positions 0, 1, and 2 — the character at index 3 ('l') is not included.
Omitting the Start or Stop
Leave out start to begin from the very first character, or leave out stop to continue to the very last character.
my_string[:] is a common idiom for copying a string (though strings are immutable in Python, so it simply returns the same value).
Negative Indices
Negative indices count backwards from the end of the string. -1 refers to the last character, -2 to the second-to-last, and so on.
A useful pattern: my_string[-n:] always gives you the last n characters, regardless of how long the string is.
The Step Parameter
The third slice argument is the step. It controls how many positions Python advances after each character it picks.
Reversing a String
Set the step to -1 to iterate right-to-left. This is the idiomatic way to reverse a string in Python:
You can combine a negative step with start and stop indices. Remember: when the step is negative, start must be greater than stop.
my_string = "Hello, World!"
print(my_string[10:2:-1]) # 'lroW ,ol' — from index 10 down to (not including) index 2See the Reverse a String chapter for more techniques, including reversed() and ''.join().
Combining Start, Stop, and Step
All three parts work together. Think of the slice as a for loop that starts at start, stops before stop, and increments by step.
Out-of-Range Indices
Unlike direct indexing (which raises an IndexError for an out-of-range index), slicing handles out-of-range values gracefully by clamping them to the string boundaries.
my_string = "Hello, World!"
# Stop index beyond the string length — no error
print(my_string[7:100]) # 'World!'
# Start index beyond the string length — returns empty string
print(my_string[50:60]) # ''
# Direct index access would raise IndexError:
# print(my_string[100]) # IndexError: string index out of rangeThis makes slicing safe for "give me up to N characters" patterns without needing to check len() first.
Practical Examples
Extract a file extension
filename = "report.pdf"
extension = filename[-3:]
print(extension) # 'pdf'Extract the domain from an email address
email = "[email protected]"
at_index = email.index("@")
domain = email[at_index + 1:]
print(domain) # 'example.com'Truncate a long string with an ellipsis
def truncate(text, max_length):
if len(text) <= max_length:
return text
return text[:max_length - 3] + "..."
print(truncate("Hello, World!", 8)) # 'Hello...'
print(truncate("Hi", 8)) # 'Hi'Check whether a string is a palindrome
word = "racecar"
is_palindrome = word == word[::-1]
print(is_palindrome) # TrueQuick Reference
| Expression | Meaning |
|---|---|
s[a:b] | Characters from index a up to (not including) b |
s[:b] | From the start up to (not including) b |
s[a:] | From index a to the end |
s[:] | Full copy |
s[a:b:n] | Every n-th character from a to b |
s[::-1] | Reversed string |
s[-n:] | Last n characters |
s[:-n] | Everything except the last n characters |
What to Read Next
- Python Strings — string creation, indexing, and immutability
- String Methods —
upper(),strip(),split(),replace(), and more - Modify Strings — techniques for transforming string content
- Concatenate Strings — joining strings with
+andjoin() - Escape Characters —
\n,\t,\\, and other special sequences - Format Strings — embedding values in strings with f-strings and
.format()