杰瑞科技汇

Python中string find()怎么用?

Of course! The find() method is a fundamental string method in Python used to locate the first occurrence of a substring.

Python中string find()怎么用?-图1
(图片来源网络,侵删)

Here’s a complete guide covering its syntax, behavior, and examples, along with important alternatives like index() and regular expressions.


The str.find() Method

The find() method searches for a substring within a string and returns the lowest index where the substring is found. If the substring is not found, it returns -1.

Syntax

string.find(substring, start, end)

Parameters

  • substring (required): The substring you want to search for.
  • start (optional): The index number where the search begins (inclusive). The default is 0.
  • end (optional): The index number where the search ends (exclusive). The default is the end of the string.

Return Value

  • Integer: The starting index of the first occurrence of the substring.
  • -1: If the substring is not found in the specified range.

Basic Examples

Example 1: Simple Search

sentence = "Hello, welcome to the world of Python."
# Find the index of "world"
index = sentence.find("world")
print(f"The index of 'world' is: {index}")
# Output: The index of 'world' is: 18
# Find a substring that doesn't exist
index_not_found = sentence.find("Java")
print(f"The index of 'Java' is: {index_not_found}")
# Output: The index of 'Java' is: -1

Example 2: Using the start Parameter

Let's find the second occurrence of "o" by starting the search after the first one.

text = "banana and orange"
# Find the first 'o'
first_o = text.find("o")
print(f"First 'o' found at index: {first_o}")  # Output: 7
# Find the second 'o' by starting the search at index 8
second_o = text.find("o", first_o + 1)
print(f"Second 'o' found at index: {second_o}") # Output: 13

Example 3: Using Both start and end Parameters

You can limit the search to a specific portion of the string.

Python中string find()怎么用?-图2
(图片来源网络,侵删)
long_sentence = "This is a long sentence. We will search within this sentence."
# Search for the word "sentence" only in the first half of the string
# The first half ends at index 25 (the space before "We")
index = long_sentence.find("sentence", 0, 25)
print(f"Found 'sentence' at index: {index}")
# Output: Found 'sentence' at index: 17

Key Characteristics and Best Practices

Case-Sensitivity

find() is case-sensitive. It will not find "Python" if you search for "python".

code = "Learn PYTHON, not python."
index = code.find("python")
print(f"Index of 'python': {index}") # Output: Index of 'python': -1

Checking if a Substring Exists

Because find() returns -1 for a failed search, it's a great way to check for the existence of a substring without causing an error (unlike the index() method, which we'll see next).

def contains_word(text, word):
    if text.find(word) != -1:
        return True
    return False
print(contains_word("Hello world", "world"))   # Output: True
print(contains_word("Hello world", "planet")) # Output: False

Handling Empty Substrings

If you search for an empty string (), find() will return the start index.

my_string = "Hello"
print(my_string.find(""))  # Output: 0
print(my_string.find("", 2)) # Output: 2

find() vs. index() vs. in

This is a very common point of confusion for beginners.

Python中string find()怎么用?-图3
(图片来源网络,侵删)
Method What it Does If Not Found... Use Case
str.find() Returns the starting index. Returns -1. When you need the index but also want to handle "not found" cases gracefully (e.g., in an if statement).
str.index() Returns the starting index. Raises a ValueError. When you expect the substring to be there and want the program to crash loudly if it's not. Good for data validation.
in operator Returns True or False. N/A (returns False). When you only need to know if something exists, not where it is.

Example Comparison

my_string = "This is a test."
# Using find()
print(f"find(): {my_string.find('test')}")      # Output: find(): 10
print(f"find(): {my_string.find('python')}")   # Output: find(): -1
# Using index()
try:
    print(f"index(): {my_string.index('test')}")    # Output: index(): 10
    print(f"index(): {my_string.index('python')}") # This will raise an error
except ValueError:
    print("index(): 'python' not found!")
# Using 'in'
print(f"'test' in string: {'test' in my_string}")      # Output: 'test' in string: True
print(f"'python' in string: {'python' in my_string}")  # Output: 'python' in string: False

Finding All Occurrences of a Substring

find() only finds the first occurrence. To find all, you need to use a loop, repeatedly calling find() and updating the start index.

def find_all_occurrences(text, substring):
    """Finds all starting indices of a substring in a text."""
    occurrences = []
    start = 0
    while True:
        start = text.find(substring, start)
        if start == -1:
            break
        occurrences.append(start)
        # Move past the found substring to avoid infinite loop
        start += len(substring)
    return occurrences
poem = "Roses are red, violets are blue, sugar is sweet, and so are you."
indices = find_all_occurrences(poem, "are")
print(f"All occurrences of 'are' are at indices: {indices}")
# Output: All occurrences of 'are' are at indices: [9, 22]

Advanced: Using Regular Expressions (re module)

For complex pattern matching (e.g., finding all "are" or "ar" words), Python's re module is much more powerful.

The re.finditer() function is perfect for finding all occurrences and their positions.

import re
poem = "Roses are red, violets are blue, sugar is sweet, and so are you."
# Find all occurrences of "are" (as a whole word)
# \b is a "word boundary"
pattern = r"\bare\b"
matches = re.finditer(pattern, poem)
all_indices = [match.start() for match in matches]
print(f"Using regex, found 'are' at indices: {all_indices}")
# Output: Using regex, found 'are' at indices: [9, 22, 45]

Summary

Method Best For Key Feature
str.find() Finding the first index of a substring and handling "not found" cases. Returns -1 on failure.
str.index() Finding the first index when you expect the substring to be present. Raises ValueError on failure.
in operator Checking for the existence of a substring (True/False). Simple, readable, and efficient for existence checks.
re.finditer() Finding all occurrences of complex patterns (regular expressions). Extremely powerful for pattern matching.

For most day-to-day tasks, find() is the right choice when you need the index, and the in operator is best when you just need a yes/no answer.

分享:
扫描分享到社交APP
上一篇
下一篇