Python String Slicing: The Ultimate Step-by-Step Guide for Beginners
Understanding String Slicing in Python
String slicing allows you to extract a portion (substring) from a string using a specific index range. The basic syntax is string[start:stop:step].
How Python Indexing Works
Consider the string "PYTHON". Python supports both positive (forward) and negative (backward) indexing.
| Positive Index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| Character | P | Y | T | H | O | N |
| Negative Index | -6 | -5 | -4 | -3 | -2 | -1 |
The Three Parameters
- start: The beginning index of the slice (inclusive). Defaults to 0.
- stop: The ending index of the slice (exclusive). The character at this index is not included.
- step: The increment size. Defaults to 1.
Common Examples
Python Code
text = "PYTHON"
# 1. Basic Slicing (Get 'TYH')
# Starts at index 1 ('Y'), stops before index 4 ('O')
print(text[1:4]) # Output: YTH
# 2. Omitting Start (Get 'PYTH')
# Automatically starts from index 0
print(text[:4]) # Output: PYTH
# 3. Omitting Stop (Get 'THON')
# Automatically goes to the very end
print(text[2:]) # Output: THON
# 4. Using a Step (Get 'PTO')
# Skips every 2nd character
print(text[0:6:2]) # Output: PTO
# 5. Negative Indexing (Get 'HO')
# Starts at -3 ('H'), stops before -1 ('N')
print(text[-3:-1]) # Output: HO
# 6. Reversing a String
# A negative step moves backward through the string
print(text[::-1]) # Output: NOHTYP
Comments
Post a Comment