Python String Slicing
String slicing in Python allows you to extract a portion (substring) of a string using a simple and powerful syntax. This is especially useful when you want to manipulate or analyze parts of a string.
In this tutorial, you’ll learn:
- What string slicing is
- How to use slicing syntax
- Common slicing patterns
- Real-world examples
What is String Slicing?
Slicing means extracting a subset of a sequence (like a string, list, or tuple). In Python, strings are zero-indexed arrays of characters. You can slice strings using bracket notation and a colon (:
).
Basic Syntax:
string[start:stop]
- start: Index where the slice starts (inclusive)
- stop: Index where the slice ends (exclusive)
- If omitted, Python assumes the start is
0
, and the end is the length of the string.
Basic String Slicing Examples
text = "Python Programming"
print(text[0:6]) # Output: Python
print(text[7:18]) # Output: Programming
Omitting Start or End
You can omit start
or stop
to slice from beginning or to the end:
text = "Hello, World!"
print(text[:5]) # Output: Hello (start from index 0)
print(text[7:]) # Output: World!
Negative Indexing
Negative numbers count from the end of the string:
text = "Python"
print(text[-3:]) # Output: hon (last 3 characters)
print(text[:-3]) # Output: Pyt (everything except last 3)
Slicing with Step Value
You can add a step to control how many characters to skip:
text = "abcdef"
print(text[::2]) # Output: ace (every 2nd character)
print(text[1::2]) # Output: bdf (starting from index 1)
Syntax with step:
string[start:stop:step]
Reversing a String Using Slicing
One of the most elegant tricks in Python:
text = "Python"
reversed_text = text[::-1]
print(reversed_text) # Output: nohtyP
Real-World Examples
Example 1: Extracting a file extension
filename = "document.pdf"
extension = filename[-3:]
print(extension) # Output: pdf
Example 2: Get the first name from a full name
fullname = "John Doe"
first_name = fullname[:4]
print(first_name) # Output: John
Tips & Notes
- Indexes start at
0
. - The stop index is not included in the result.
- You can combine positive and negative indexes.
- Slicing returns a new string; it does not modify the original.
Summary Table
Expression | Description |
---|---|
s[start:stop] | Slice from start to stop-1 |
s[:stop] | Slice from beginning to stop-1 |
s[start:] | Slice from start to end |
s[-n:] | Last n characters |
s[::-1] | Reverse the string |
s[::step] | Skip characters based on step size |