Python String find() method
Last Updated :
20 Jun, 2024
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'))
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:
- 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.
- 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")
OutputSubstring '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))
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)
OutputTotal 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.")
OutputThe 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]
Please Login to comment...