How to get the position of a character inside a string in Python
In this tutorial, we are going to learn about how to get the position of a character inside a given string using Python.
Getting the character position
To get the position of a character in a given string, we can use the built-in find()
method in Python.
Here is an example, that gets the position (or index) of a character v
.
name = 'olive'
index = name.find('v')
print(index) # 3
Similarly, we can also use the index()
method to find the position of a character inside a string.
name = 'olive'
index = name.index('v')
print(index) # 3
The difference between find()
and index()
is , find()
returns -1
if a given character is not found in a string where index()
returns ValueError
.