Python string find

The Python string find function is used to return the index position of the first occurrence of a specified string. It returns -1 if the specified string is not found.

In this section, we discuss how to write a find string Function with an example. The index position in this method start from 0, Not 1. The syntax of the find function is:

String_Value.find(Substring, Starting_Position, Ending_Position)
  • String_Value: Valid literal.
  • Substring you want to search for.
  • Starting_Position (optional): If you want to specify the starting point (starting index position), then Please specify the value here. If you omit this parameter, the function considers Zero as a starting position.
  • Ending_Position (optional): If you want to specify the endpoint (Ending index position), then Please specify the value here. If you Omit this parameter, the find Function considers the highest number.

Python find substring in a string Example

The following set of examples helps you understand the find string.

In the first statement, Str2 discovers all occurrences of a substring ‘abc’ inside the Str1 using the find Method and prints the output.

If the function does not discover the specified substring inside the Str1, it returns -1. We used Str4 to explain this.

The Python string find function allows us to use the Starting index position of the substring. We can increase performance by specifying the starting index position as 12 in Str5.

It allows us to use Starting and ending indices. By providing the starting and ending index positions, we can increase the performance. The following Str6 Python statement starts looking for ‘abc’ from 12.

The. last line Str7 is returning -1 because this string find function starts looking from 12 (means the first abc skipped) and ends at index position 21. As we all know, the second abc is in position 22.

Str1 = 'We are abc working at abc company';
Str2 = Str1.find('abc')
print('First Output of a method is = ', Str2)

# Performing directly
Str3 = 'Get Tutorial at Tutorial Gateway'.find('Tutorial')
print('Second Output of a method is = ', Str3)

# Searching for Not existing Item
Str4 = Str1.find('Tutorial')
print('Third Output = ', Str4)

# Using First Index
Str5 = Str1.find('abc', 12)
print('Fourth Output = ', Str5)

# Using First & Second
Str6 = Str1.find('abc', 12, len(Str1) -1)
print('Fifth Output = ', Str6)

# Using First & Second while looking at Non existing one
Str7 = Str1.find('abc', 12, 21)
print('Sixth Output of this method is = ', Str7)
Python Find