The Wayback Machine - https://web.archive.org/web/20240724194755/https://www.geeksforgeeks.org/python-string-find/
Open In App

Python String find() method

Last Updated : 20 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string.

Example

Python
# initializing a string
word = 'find me if you can'
# using string find() method
print(word.find('me'))

Output
5

Python String find() Method Syntax

str_obj.find(sub, start, end)

Parameters

  • sub: Substring that needs to be searched in the given string. 
  • start (optional): Starting position where the substring needs to be checked within the string. 
  • end (optional): The end position is the index of the last value for the specified range. It is excluded while checking. 

Return

Returns the lowest index of the substring if it is found in a given string. If it’s not found then it returns -1.

Note:

  1. If the start and end indexes are not provided then by default it takes 0 and length-1 as starting and ending indexes where ending indexes are not included in our search.
  2. The find() method is similar to the index(). The only difference is find() returns -1 if the searched string is not found and index() throws an exception in this case.

What is the String find() Method?

String find() is an in-built function in Python that is used to find the index of a substring within a given string.

It is a very easy and useful string function, that can help us find a given substring. It returns the index of the substring if it is found in the string, but if the substring is not present in the string it returns -1.

How to use the string find() method?

String.find() method returns the index of a substring in a string and using the find() function is very easy. You just need to call the find function with the object string and pass the substring as a parameter.

Let’s understand it better with an example:

Python
string = " hello world is the first code of every programmer"
print(string.find("first"))

Output

20

More Examples on String find() Method

Let’s look at some string find() method examples with programs and understand how to use the string find() method with some variations. Below are the ways by which we can use the string find method in Python:

  • With No start and end Argument
  • With start and end Arguments
  • Total Occurrences of a Substring
  • Check if the Substring Exists

1. find() With No start and end Argument

When the find() function is called without specifying the start and end arguments, it searches for the first occurrence of the substring within the entire input string from the beginning to the end.

In this example, the find() method is used on the string ‘geeks for geeks’ to locate the index of the first occurrence of the substrings ‘geeks’ and ‘for’. The method returns the starting index of the substring if found, and -1 otherwise.

Python
word = 'geeks for geeks'

# returns first occurrence of Substring
result = word.find('geeks')
print("Substring 'geeks' found at index:", result)

result = word.find('for')
print("Substring 'for ' found at index:", result)

# How to use find()
if word.find('pawan') != -1:
    print("Contains given substring ")
else:
    print("Doesn't contains given substring")

Output
Substring 'geeks' found at index: 0
Substring 'for ' found at index: 6
Doesn't contains given substring

2. find() With start and end Arguments

When the find() function is called with the start and/or end arguments, it searches for the first occurrence of the substring within the specified portion of the input string, delimited by the start and/or end indices.

Python
word = 'geeks for geeks'

# Substring is searched in 'eks for geeks' 
print(word.find('ge', 2)) 

# Substring is searched in 'eks for geeks' 
print(word.find('geeks ', 2)) 

# Substring is searched in 's for g' 
print(word.find('g', 4, 10)) 

# Substring is searched in 's for g' 
print(word.find('for ', 4, 11)) 

Output
10
-1
-1
6

3. Total Occurrences of a Substring using find()

find() function can be used to count the total occurrences of a word in a string.

Python
main_string = "Hello, hello, Hello, HELLO! , hello"
sub_string = "hello"
count_er=0
start_index=0
for i in range(len(main_string)):
  j = main_string.find(sub_string,start_index)
  if(j!=-1):
    start_index = j+1
    count_er+=1
print("Total occurrences are: ", count_er)  

Output
Total occurrences are:  2

4. Check if the Substring Exists using the find() Function

In this example, the code uses the find() method to check if the substring “Python” exists in the string “Python is powerful.” If the substring is found, it prints a message indicating its existence; otherwise, it prints a message stating that the substring does not exist in the text.

Python
text = "Python is powerful."
substring = "Python"

if text.find(substring) != -1:
    print(f"The substring '{substring}' exists in the text.")
else:
    print(f"The substring '{substring}' does not exist in the text.")

Output
The substring 'Python' exists in the text.

We have covered the definition, syntax, and different examples of the Python string find() method. This function is very useful for finding substrings within a string. It is a very simple and easy-to-use string method.

Read other Python String Methods

Read more articles related to how to find a substring in a string:

Python String find() method – FAQs

How do you update values in a list in Python?

You can update values in a list by accessing the elements using their index and then assigning a new value. Here’s an example:

# Original list
my_list = [1, 2, 3, 4, 5]

# Update the value at index 2
my_list[2] = 10

print(my_list) # Output: [1, 2, 10, 4, 5]

How do I replace a range of values in a list?

You can replace a range of values using slicing. Here’s how:

# Original list
my_list = [1, 2, 3, 4, 5]

# Replace values from index 1 to 3
my_list[1:4] = [20, 30, 40]

print(my_list) # Output: [1, 20, 30, 40, 5]

How do you replace a substring in a list in Python?

If you want to replace a substring in each string of a list, you can use a list comprehension:

# Original list
my_list = ["apple", "banana", "cherry"]

# Replace substring 'a' with 'o' in each string
my_list = [s.replace('a', 'o') for s in my_list]

print(my_list) # Output: ['opple', 'bonono', 'cherry']

What is the best way to replace values in a list with another list?

To replace values in a list with another list, you can use slicing. This method is flexible and allows you to replace any segment of the list with another list:

# Original list
my_list = [1, 2, 3, 4, 5]

# New values to insert
new_values = [10, 20, 30]

# Replace values from index 1 to 3
my_list[1:4] = new_values

print(my_list) # Output: [1, 10, 20, 30, 5]

Can I use the map function to replace values in a list?

Yes, you can use the map function to replace values in a list based on a specified condition or transformation. The map function applies a given function to all items in the input list:

# Original list
my_list = [1, 2, 3, 4, 5]

# Function to replace values
def replace(x):
if x % 2 == 0:
return x * 2
else:
return x

# Use map to apply the function
new_list = list(map(replace, my_list))

print(new_list) # Output: [1, 4, 3, 8, 5]


Previous Article
Next Article

Similar Reads

Python string length | len() function to find string length
The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method. Example: C/C++ Code string = "Geeksforgeeks" print(len(string)) Output13String len() Syntax len(string) Parameter String: string of which you want to find the length. Return: It returns
3 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).Right (Or clockwise) rotate the given string by d elements (where d <= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
String Alignment in Python f-string
Text Alignment in Python is useful for printing out clean formatted output. Some times the data to be printed varies in length which makes it look messy when printed. By using String Alignment the output string can be aligned by defining the alignment as left, right or center and also defining space (width) to reserve for the string. Approach : We
2 min read
String to Int and Int to String in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting a string to int and int to string. Converting a string to an int If we want to convert a number that is represented in the string to int, we have to use the int() function. This function is used
2 min read
Pad or fill a string by a variable in Python using f-string
f-string stands for formatted string. It had come up by Python Version 3.6 and rapidly used to do easy formatting on strings. F-string is a string literal having syntax starts with f and followed by {}. That placeholder used for holding variable, that will be changed upon the variable names and their values respectively. There are already strings f
4 min read
Python String Formatting - How to format String?
String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string. You will learn different methods of string formatting with examples for better understanding. Let's look at them now! How to Format Strings in PythonThere are five different ways to perform stri
8 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg