Accessing Characters in Strings
In Python, we can access individual characters of a string using indexing. Indexing refers to the position of a character in a string.
Python uses zero-based indexing, meaning the first character is at position 0. Indexes can be positive (from left to right) or negative (from right to left).
Syntax:
string_name[index]
Index Positions in a String
This shows how positive and negative indexing works on a string:
# Positive index: 0 1 2 3 4 5 6
# -----------------------------
# Characters: 'S' 'h' 'i' 'k' 's' 'h' 'a'
# Negative index: -7 -6 -5 -4 -3 -2 -1
Note:
- Positive indexing starts from
0and moves from left to right. - Negative indexing starts from
-1and moves from right to left. - Each character in the string can be accessed using these index positions.
Example 1:
name = "ShikshaSanchar"
print(name[0]) # First character
print(name[4]) # Fifth character
print(name[-1]) # Last character
Output:
S
h
r
Explanation:
name[0]gives the first character, which is 'S'.name[4]accesses the fifth character, which is 'h'.name[-1]accesses the last character from the end, which is 'r'.
Example 2:
name = "Mukesh>"
print(name[0]) # First character
print(name[3]) # Fourth character
print(name[-1]) # Last character
Output:
M
e
h
Explanation:
name[0]gives the first character, which is 'M'.name[3]accesses the fourth character, 'e'.name[-1]accesses the last character from the end, 'h'.
Summary:
- Use square brackets
[]to access characters in a string. - Indexing starts from 0 (left to right).
- Negative indexing starts from -1 (right to left).
- Invalid index will raise an
IndexError.