Python String find()

Filed Under: Python

Python String find() method is used to find the index of a substring in a string.

Python String find()

The syntax of find() function is:


str.find(sub[, start[, end]])

This function returns the lowest index in the string where substring “sub” is found within the slice s[start:end].

start default value is 0 and it’s an optional argument.

end default value is length of the string, it’s an optional argument.

If the substring is not found then -1 is returned.

We should use the find() method when we want to know the index position of the substring. For checking if a substring is present, we can use in operator.

Python String find() examples

Let’s look at some simple examples of find() method.


s = 'abcd1234dcba'

print(s.find('a'))  # 0
print(s.find('cd'))  # 2
print(s.find('1', 0, 5))  # 4
print(s.find('1', 0, 2))  # -1

Python String rfind()

Python string rfind() method is similar to find(), except that search is performed from right to left.


s = 'abcd1234dcba'

print(s.rfind('a'))  # 11
print(s.rfind('a', 0, 20))  # 11
print(s.rfind('cd'))  # 2
print(s.rfind('1', 0, 5))  # 4
print(s.rfind('1', 0, 2))  # -1

Find all indexes for substring

Python string find() and rfind() returns the first matched index. We can define a custom function to find all the indexes where the substring is found.


def find_all_indexes(input_str, search_str):
    l1 = []
    length = len(input_str)
    index = 0
    while index < length:
        i = input_str.find(search_str, index)
        if i == -1:
            return l1
        l1.append(i)
        index = i + 1
    return l1


s = 'abaacdaa12aa2'
print(find_all_indexes(s, 'a'))
print(find_all_indexes(s, 'aa'))

Output:


[0, 2, 3, 6, 7, 10, 11]
[2, 6, 10]
You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: str.find()

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages