Python String find() Method

First of all, let's Revise what String is in Python:

A string is a collection of characters that Python defines as contained in one two or three quotation marks. It is a line of Unicode characters with set lengths. This means that after a string has been created you can not change its value.

In Python, you can show text numbers symbols and other forms of data using strings. They are frequently used to store and modify textual material read and write files manage user input, and produce output in a certain format.

Concatenation slicing and indexing are just a few of the operations Python strings can do. Texts may also be changed and edited using various built-in string techniques, such as character replacement, case conversions to uppercase or lowercase, or substring.

Ex:

Many different functions are used to modify strings or to operate with Strings.

One of them is the find() method.

find() Function in String

Python finds () method finds a substring in the whole String and returns the index of the first match. It returns -1 if the substring does not match.

Syntax:

The syntax of the find() method is as follows:

Parameters:

Where:

  • String is the String in which you want to search for the substring
  • Substring is the String you want to search for
  • Start is the index from which the search should begin (optional, defaults to 0)
  • End is the index at which the search should end (optional, defaults to the end of the String)

Return Type:

The find() method returns the index of the first occurrence of that substring in the given range. In case the substring is not found, it returns -1.

Some Examples:

Here's an example of using the find() method to search for a substring within a string:

Example 1:

Program to find a substring in a string:

Output:

7

Example 2:

Finding a substring in a string with start and end indices:

Output:

3

Example 3

How to find a substring that is not present in a string:

Output:

-1

Example 4:

Finding a substring in a string with multiple occurrences:

Output:

2
3
10

Next TopicPython Strings




Latest Courses