How to access characters in Python?
In Python, you can access individual characters in a string using indexing. Strings are sequences of characters, and each character in a string has a specific position known as its index.
Python uses zero-based indexing, which means the first character is at index 0, the second character is at index 1, and so on.
# Accessing characters at specific indices
first_character = message[0]
Syntax
To access a character at a specific index in a string, you can use square brackets [ ]
along with the index number.
# Syntax to access character at index i
character = string_variable[i]
How to access characters in Python
# Define a string
message = "Hello, Python!"
# Accessing characters at specific indices
first_character = message[0]
second_character = message[1]
last_character = message[-1] # Negative index accesses characters from the end
# Output the characters
print("First character:", first_character) # Output: H
print("Second character:", second_character) # Output: e
print("Last character:", last_character) # Output: !