"Author's Homepage": Shibie Sanri wyx
"Author's Profile": CSDN top100, Alibaba Cloud Blog Expert, Huawei Cloud Share Expert, Network Security High-quality Creator
"Recommended Column": Xiaobai Zero Basic "Python Beginner to Master"
find
find() can "check" whether the string "contains the specified string"
grammar
string.find( str, start, end)
parameter
- str : (required) specifies the string to be detected
- start : (optional) start index, default is 0
start = 0
- end : (optional) end index, defaults to the length of the string
end = len(string)
return value
- Returns the index of the string if it "contains" the string
- Returns -1 if the string "does not contain"
Example: Check if the string 'hello world' contains the string 'e'
str1 = 'hello world'
print(str1.find('e'))
output:
1
1. Specify the search location
Only start is given, end is not given , and the "end" of the string is searched by default , and the search range is[start, 末尾]
For example, starting from index 3 and ending at the end, check whether the string 'e' exists
str1 = 'hello hello'
print(str1.find('e', 3))
output:
7
As can be seen from the result, 'e' exists, and the index position of 'e' is returned.
Give start and end at the same time , the search range includes the head but not the tail[start, end)
For example, starting from index 3 and ending at index 7, check whether the string 'e' exists
str1 = 'hello hello'
print(str1.find('e', 3, 7))
print(str1.find('e', 3, 8))
output:
-1
7
It can be seen from the results that the index of 'e' is 7. When the end is 7, because the search "including head but not tail" is not found, it returns -1.
2. The parameter is a negative number
start and end can be "negative numbers" .
Starting from the 4th from the right and ending at the end, check if 'e' exists
str1 = 'hello hello'
print(str1.find('e', -4))
output:
7
Starting from the 4th from the right and ending with the 3rd from the right, check if 'e' exists
str1 = 'hello hello'
print(str1.find('e', -4, -3))
print(str1.find('e', -4, -4))
output:
7
-1
3. Out of range
If the searched index "exceeds" the "length" of the string , -1 is returned instead of an error.
No error will be reported even if the length of the searched substring exceeds the length of the string.
str1 = 'hello'
print(str1.find('e', 11))
print(str1.find('hello world'))
output:
-1
-1
3. What is the difference between find() and index()?
Both find() and index() can detect the existence of a string, but if the value cannot be found, find() will return -1, and index() will report an error ValueError: substring not found
str1 = 'hello hello'
print(str1.find('a'))
print(str1.index('a'))
output:
4. What is the difference between find() and rfind()?
Both find() and rfind() can detect whether a string exists. The difference is that find() starts searching from the "left side" , while rfind() starts searching from the "right side" .
str1 = 'hello hello'
print(str1.find('e'))
print(str1.rfind('e'))
output:
1
7