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. Here is an example:

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".

Watch a course Python - The Practical Guide

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.

string = "Hello World"
char = "z"

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