To get a substring of a string in Python, you can use string slicing with the syntax [start:end:step]. Here’s how it works:
Basic Syntax
substring = string[start : end] # Characters from index `start` (inclusive) to `end` (exclusive)
Examples
1. Extract “World” from “Hello, World!”
s = "Hello, World!"
print(s[7:12]) # Output: "World" (indices 7 to 11)
2. First 5 Characters
print(s[:5]) # Output: "Hello" (indices 0 to 4)
3. From Index 7 to End
print(s[7:]) # Output: "World!" (indices 7 to end)
4. Last 6 Characters
print(s[-6:]) # Output: "World!" (last 6 characters)
Key Rules
- Indices start at 0.
startis inclusive,endis exclusive.- Omit
startto start from the beginning (s[:end]). - Omit
endto go to the end (s[start:]). - Use negative indices to count from the end (
-1= last character).
Advanced: Step Value
Add a third parameter (step) to skip characters:
print(s[::2]) # Every 2nd character: "Hlo ol!"
print(s[::-1]) # Reverse the string: "!dlroW ,olleH"
Common Use Cases
| Use Case | Example | Output |
|---|---|---|
First n characters | s[:5] | "Hello" |
Last n characters | s[-6:] | "World!" |
From index i to j | s[7:12] | "World" |
Every k-th character | s[::2] | "Hlo ol!" |
| Reverse a string | s[::-1] | "!dlroW ,olleH" |
Edge Cases
- If
start > end, returns an empty string ("") unless using a negativestep. - Out-of-range indices are handled gracefully (e.g.,
s[0:100]returns the entire string).
Summary
Use slicing to extract substrings by specifying start, end, and optional step. Python’s flexible syntax handles most use cases intuitively!