In Python, strings are sequences of characters. Each character in the string has a specific position (index), starting from 0
for the first character. Python also supports negative indexing, where -1
refers to the last character.
# Example 1: Accessing characters using positive index
text = "Python"
print(text[0]) # Output: 'P'
print(text[2]) # Output: 't'
# Example 2: Accessing characters using negative index
text = "Python"
print(text[-1]) # Output: 'n'
print(text[-3]) # Output: 'h'
# Example 3: IndexError when index is out of range
text = "Hi"
# print(text[5]) # Uncommenting this will raise IndexError
# Example 4: Loop through characters using index
text = "Code"
for i in range(len(text)):
print(f"Character at index {i} is {text[i]}")
# Example 5: Using indexing with user input
name = input("Enter your name: ")
if len(name) >= 2:
print("Second character of your name:", name[1])