learn how to use python string find() with example

The find() method in Python is used to find the index of a substring within a string. It is part of the string class and provides a way to search for the occurrence of a specified value.

Syntax:

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

str: is the string on which the method is called.

sub: is the substring that you’re searching for.

start and end are optional parameters that specify the range in which you’re searching. start is the index where the search will start, and end is the index where the search will stop. Note that Python uses 0-based indexing, meaning the first character is at position 0.

How to use the find() method:

str = "Hello, world!"
print(str.find("world")) # Output: 7
print(str.find("Earth")) # Output: -1

Example 1

Finding the starting index of a substring in a string.

sentence = "Python is a high-level, general-purpose programming language."
index = sentence.find("general-purpose")
print(index) # Output: 23

Example 2

searching for data between the 10th and 30th characters in the string.

sentence = "Python is widely used in data analysis."
index = sentence.find("data", 10, 30)
print(index) # Output: 23

Example 3

Using find() to check if fox is present in the sentence.

sentence = "The quick brown fox jumps over the lazy dog."
if sentence.find("fox") != -1:
  print("The substring 'fox' was found in the sentence.")
else:
  print("The substring 'fox' was not found in the sentence.")

Leave a Reply

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