Accessing Characters in Python Strings
To access individual characters in a string, you can use the index operator [] to retrieve the character at a specific position. In Python, strings are character sequences, with each character having a unique index value starting from 0.
For example, to access the first character “H” in the string “Hello”, you can use the index value of 0 to retrieve it.
string = "Hello"
first_char = string[0]
print(first_char) # Output: H
Similarly, negative index values can be used to access characters starting from the end of a string. For example, to access the last character “d” in the string “World”, you can use the index value -1:
string = "World"
last_char = string[-1]
print(last_char) # Output: d
Accessing individual characters in a string using an index value is a convenient and common operation that allows us to easily retrieve and manipulate specific characters in the string.