Find index of character in string Python
In this post, you will learn how to find the index of a character in a string using the Python programming language.
A string is a sequence of characters. In Python, strings are immutable, indexable, and iterable. Strings in Python are surrounded by either single quotation marks, or double quotation marks. Python has a set of built-in methods that we can use on strings. All string methods return new values. They do not change the original string. Here, we have used the following string methods to find the index of a character in a string.
- str.find()
- str.rfind()
- str.index()
- str.rindex()
- re.search()
Python str.find() method
The str.find() method of Python finds the first occurrence of the specified value within the slice s[start:end]. It is almost the same as the index() method. The only difference is that the index() method raises an exception if the value is not found.
str.find(sub,start,end)
In the given Python code, we create a string variable str1 and call the find() method on it to find the occurrence of "r".
str1="etutorialspoint"
print(str1.find("r"))
# Output: 5
Python str.rfind() method
The rfind() method of Python finds the last occurrence of the specified value. This method returns -1 if the value is not found.
str.rfind(sub, start, end)
Example
string = "etutorialspoint"
print(string.rfind("s"))
# Output: 9
Python str.index() method
The index() method of Python finds the first occurrence of the specified value. If the substring is not found, it raises an exception.
string.index(value, start, end)
Example
string = "etutorialspoint"
print(string.index("l"))
# Output: 8
Python str.rindex() method
The rindex() method of Python finds the last occurrence of the specified value. This method raises an exception if the value is not found.
str.rindex(sub, start, end)
Example
string = "etutorialspoint"
print(string.rindex("a"))
# Output: 7
Python re.search() method
The re.search() function of Python will search the regular expression pattern and return the first occurrence.
re.search(pattern, string, flags=0)
Example
import re
str1 = 'etutorialspoint'
pattern = 'u'
match=(re.search(pattern, str1))
#Returns match object
print (match)
Output of the above code:
<re.Match object; span=(2, 3), match='u'>
Related Articles
Convert array to list Python
Python loop through list
Difference between tuple and list in Python
Convert string to list Python
Remove last element from list Python
Convert list to string Python
Convert Python list to numpy array
Remove element from list Python
Python dict inside list
Check if list is empty Python
Python iterate list with index
Python iterate list with index
Python split string by comma
Printing Simple Diamond Pattern in Python
Stemming and Lemmatization in Python
Python | Generate QR Code using pyqrcode module