Find index of character in string python | Example code

Use Python find() method to get the index value of character in given string. This method returns the index of a char inside the string if found. And If the char is not found, it raises an exception.

Example find the index of a character in string python

Simple example code.

text = 'Python is Best'

# find the index of i
res = text.find('i')

print(res)

Output:

Find index of character in string python

You can also use index() method

text = 'Python is Best'

#  the index of i
res = text.index('i')

print(res)

Output: 7

The difference between the find() and index() is what happens when the search string isn’t found. find() returns -1 and index() raises ValueError.

Do comment if you have any doubts and suggestions on this Python char string program.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.