Slicing in Strings
Slicing in strings means extracting a part (substring) from the original string.
It uses start:stop:step inside square brackets and does not modify the original string.
The start, end & step index are seperated using a colon (:).
Note:
Slicing does not include the character at the
stop index.
For example, if stop = 5, it returns characters up to index 4.
Syntax:
string_name[start : stop : step]
It returns characters from start index to end index - 1.
Examples of String:
text = "ShikshaSanchar"
1. Slicing with start and stop:
print(text[0:8])
Output:
ShikshaS
Explanation:
start = 0, so starts from index 0 ('S').stop = 8, so goes up to index 7 ('S').- It excludes index
8.
2. Omitting start (defaults to 0):
print(text[:6])
Output:
Shiksh
Explanation:
- Start is empty, so it begins from index 0.
stop = 6, so ends at index 5 ('h').
3. Omitting stop (goes till end):
print(text[7:])
Output:
anchar
Explanation:
start = 7, so starts at index 7 ('a').- Stop is empty, so it goes till end of string.
4. Using step (skip characters):
print(text[::2])
Output:
Siksaaha
Explanation:
- Start and stop are empty → entire string is selected.
step = 2→ takes every 2nd character.
5. Full example with start, stop, and step:
print(text[1:10:2])
Output:
ikahS
Explanation:
start = 1→ starts at index 1 ('h').stop = 10→ ends at index 9 ('a').step = 2→ takes every 2nd character.
6. Using negative step (reverse string):
print(text[::-1])
Output:
rahcnaSahskihS
Explanation:
step = -1→ reverses the string.- Starts from end, moves backward to beginning.
Common Mistakes in String Slicing
text = "ShikshaSanchar"
# Mistake 1: start > end with positive step
print(text[10:5])
# Mistake 2: Step is 0
print(text[1:5:0])
# Mistake 3: Index beyond string length
print(text[5:100])
Output:
(empty)
ValueError: slice step cannot be zero
shaSanchar
Explanation:
-
text[10:5]gives an empty string because slicing moves left to right, but here the start index (10) is after the end index (5), so nothing gets selected. -
text[1:5:0]gives an error as step cannot be zero in slicing. -
text[5:100]works fine because if the end index is too big, Python automatically stops at the actual end of the string.
Summary of String Slicing:
- Slicing syntax:
string[start : stop : step]. - If
startis empty → begins from start of string. - If
stopis empty → continues till end. - If
stepis empty → default is 1. - Stop index is excluded.
- Use
step = -1for reverse string.