Skip to content

Python index of the character in string | Example code

  • by

Simple use the Python find function or index function to get the index of the character in the string. The difference between the two is what happens when the search string isn’t found. find() returns -1 and index() raises ValueError.

Example get index of a character in a string python

Simple example code.

Using find()

The find() method is similar to the index() method, but returns -1 if the character is not found instead of raising a ValueError.

s = 'Position of a character'

res = s.find('s')

print(res)

Using index()

The index() method returns the index of the first occurrence of a character in a string, or raises a ValueError if the character is not found.

s = 'Position of a character'

res = s.index('s')

print(res)

Output:

Python index of the character in string

Do comment if you have any doubts or suggestions on this Python index topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *