str.find(sub[, start[, end]])
时间: 2024-01-09 18:05:52 浏览: 69
find在python中的用法.docx
The `find()` method is used to find the starting index of a substring within a string. It takes one required argument, `sub`, which is the substring to be searched for. It also has two optional arguments, `start` and `end`, which specify the range of the string to be searched.
If the substring is found within the specified range, the method returns the starting index of the substring. If the substring is not found, it returns -1.
Example:
```
s = "Hello, World!"
print(s.find("o")) # Output: 4
print(s.find("l")) # Output: 2
print(s.find("z")) # Output: -1
print(s.find("o", 5, 10)) # Output: 7
```
In the first example, the method searches for the first occurrence of the letter "o" in the string and returns the index 4.
In the second example, the method searches for the first occurrence of the letter "l" in the string and returns the index 2. Note that this is the index of the first "l", not the second.
In the third example, the method searches for the letter "z" in the string and returns -1, indicating that the substring was not found.
In the fourth example, the method searches for the letter "o" in the range from index 5 to index 10 (exclusive) and returns the index 7.
阅读全文