Detailed explanation of how to use the find function in Python

In Python, the find() method is a function of string objects used to search for a substring within a string and return the index of the first occurrence of the substring. If the substring is not found, it returns -1.

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

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

Instructions for parameters:

  1. sub: the substring to be searched for.
  2. start (optional): specifies the starting position for the search, default is 0.
  3. end (optional): specifies the ending position to search, by default it is the length of the string.

Here is an example code:

str = "Hello, World!"
index = str.find("o")
print(index)  # 输出结果为 4

The find() function can also be used with iterable objects such as lists and tuples with the same syntax.

bannerAds