To find the first index of a character in a string in Python, you can use the index
method of the string.
main.py90 chars4 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.py90 chars4 lines
In this example, find("x")
will return -1 because the character 'x' is not found in the string "hello world".
gistlibby LogSnag