Python字符串.find()方法返回整数值的含义与计算方式解析
Hey there! Let's break down exactly how Python's str.find() method works, including what it returns, how that value is calculated, and how to use it to check for substring presence.
What does find() return?
The find() method returns an integer that represents the 0-based index of the first occurrence of the substring you're searching for in the original string. If the substring doesn't exist anywhere in the string, it returns -1.
Let’s walk through your code examples to make this concrete:
quote = 'Let it be, let it be, let it be' result = quote.find('let it') print("Substring 'let it':", result) # Output: 11 result = quote.find('small') print("Substring 'small ':", result) # Output: -1 # How to use find() if (quote.find('be,') != -1): print("Contains substring 'be,'") else: print("D...")
- For
'let it': The first occurrence starts at index 11 (we count from 0 in Python strings). The opening'Let it be, 'takes up the first 10 positions, so the'l'of'let it'lands at position 11. - For
'small': Since this substring isn’t present inquote, the method returns-1(the print statement has an extra space, but that doesn’t change the result here).
How is the return value calculated?
The index is always calculated relative to the start of the entire original string (starting at 0), even if you use the optional start and end parameters to narrow your search range.
For example, if you ran quote.find('let it', 12), it would only search from index 12 onward, but the returned index (23, for the next occurrence of 'let it') would still be its position in the full string—not relative to the start of your search range.
How to check if a substring exists using find()
As shown in your code snippet, the most straightforward way is to check if the return value is not equal to -1. If it’s any other integer, the substring exists in the original string:
if quote.find('be,') != -1: print("Contains substring 'be,'") # This runs, since 'be,' is present else: print("Doesn't contain substring 'be,'")
This works because -1 is the only value find() returns when the substring can’t be found.
内容的提问来源于stack exchange,提问作者Thomas

