find the first index of a character in a string in python

To find the first index of a character in a string in Python, you can use the index method of the string.

main.py
my_string = "hello world"
char_index = my_string.index("o")
print(char_index) # Output: 4
90 chars
4 lines

In this example, index("o") will return the index of the first occurrence of the character 'o' in the string "hello world". The output will be 4, as the first occurrence of "o" is at index 4 in the string.

If the character is not found in the string, the index method will raise a ValueError. To avoid this error, you can use the find method instead, which returns -1 if the character is not found.

main.py
my_string = "hello world"
char_index = my_string.find("x")
print(char_index) # Output: -1
90 chars
4 lines

In this example, find("x") will return -1 because the character 'x' is not found in the string "hello world".

related categories

gistlibby LogSnag