W3docs

How to get the position of a character in Python?

You can use the index() method to get the position of a specific character in a string.

You can use the index() method to get the position of a specific character in a string. Here is an example:

get the position of a character in Python

string = "Hello World"
char = "W"
position = string.index(char)
print(position)

This will output 6, which is the position of the character "W" in the string "Hello World".

Please note that if the specified character is not found in the string, it will raise an exception ValueError, you can use try-except block to handle that.

get the position of a character in Python and handling possible exceptions

string = "Hello World"
char = "z"

try:
    position = string.index(char)
    print(position)
except ValueError:
    print(f'{char} not found in {string}')