Indexing is the process of accessing individual characters or substrings within a string. In Python, you can access individual characters in a string using square brackets []. The index of the first character in a string is 0, and the index of the last character is len(string) - 1.
Here are some examples of indexing strings in Python:
string = "Hello, world!"print(string[0]) # Output: "H"print(string[4]) # Output: "o"print(string[-1]) # Output: "!"print(string[-3]) # Output: "l"print(string[7:12]) # Output: "world"print(string[:5]) # Output: "Hello"print(string[7:]) # Output: "world!" |
In these examples, we define a string string and then use indexing to access different parts of the string. We use positive indices to access characters from the beginning of the string, and negative indices to access characters from the end of the string. We also use slicing to extract a substring from the string.
Note that strings in Python are immutable, which means that you cannot modify the characters of a string directly. If you need to modify a string, you must create a new string with the modified contents.