String indexing in Python allows you to access individual characters in a string using their position. Here’s how it works:
Basics of Indexing
-
Zero-Based Indexing:
- Python uses zero-based indexing, meaning the first character of a string is at index
0, the second character is at index1, and so on. - For example, in the string
"Hello":His at index0eis at index1lis at index2lis at index3ois at index4
- Python uses zero-based indexing, meaning the first character of a string is at index
-
Negative Indexing:
- You can also use negative indices to access characters from the end of the string. The last character is at index
-1, the second last at-2, and so forth. - For example, in the string
"Hello":ois at index-1lis at index-2lis at index-3eis at index-4His at index-5
- You can also use negative indices to access characters from the end of the string. The last character is at index
Accessing Characters
You can access a character in a string by specifying its index in square brackets []. Here’s an example:
text = "Hello, World!"
first_character = text[0] # 'H'
last_character = text[-1] # '!'
Slicing Strings
You can also extract a substring (a slice) from a string using a range of indices. The syntax is string[start:end], where start is inclusive and end is exclusive.
text = "Hello, World!"
substring = text[0:5] # 'Hello'
Important Notes
- If you try to access an index that is out of range (e.g.,
text[100]for a string of length 13), Python will raise anIndexError. - Slicing can also be done with negative indices:
substring = text[-6:-1] # 'World'
Example
Here’s a complete example demonstrating indexing and slicing:
text = "Python Programming"
print(text[0]) # Outputs: 'P'
print(text[-1]) # Outputs: 'g'
print(text[7:18]) # Outputs: 'Programming'
print(text[:6]) # Outputs: 'Python'
print(text[7:]) # Outputs: 'Programming'
Understanding string indexing is crucial for manipulating and processing text data effectively. If you have any further questions or need more examples, feel free to ask!
