杰瑞科技汇

python strindexof

Of course! In Python, there isn't a built-in function called str.indexOf() like there is in JavaScript or Java. Instead, Python strings have a method called .index() and another very similar one called .find().

Here’s a complete guide covering both, as they are the standard ways to find the index of a substring in Python.

The .index() Method

This is the most direct equivalent to str.indexOf() in other languages. It searches the string for a specified substring and returns the index of the first occurrence.

Syntax

string.index(substring, start, end)
  • substring: The substring you want to find (required).
  • start: The starting index for the search (optional). Defaults to 0.
  • end: The ending index for the search (optional). Defaults to the end of the string.

Example

sentence = "Hello world, welcome to the universe."
# Find the index of the first occurrence of "world"
index = sentence.index("world")
print(f"The index of 'world' is: {index}")
# Output: The index of 'world' is: 6
# Find the index of "welcome", starting the search from index 10
index_welcome = sentence.index("welcome", 10)
print(f"The index of 'welcome' (starting from 10) is: {index_welcome}")
# Output: The index of 'welcome' (starting from 10) is: 13

The Crucial Difference: What Happens When the Substring is NOT Found?

This is the most important distinction between .index() and .find().

  • .index() raises a ValueError if the substring is not found.
  • .find() returns -1 if the substring is not found.

Example with .index() (and error)

sentence = "Hello world, welcome to the universe."
# This will cause an error because "python" is not in the string
try:
    index = sentence.index("python")
    print(f"The index is: {index}")
except ValueError:
    print("Error: The substring 'python' was not found in the string.")
# Output: Error: The substring 'python' was not found in the string.

Because of this, you should almost always use a try...except block if you use .index() and aren't 100% sure the substring exists.


The .find() Method (Often Safer and More Convenient)

The .find() method works exactly like .index() in terms of finding the substring, but its behavior on failure is much safer for most programming tasks.

Syntax

string.find(substring, start, end)

The parameters are identical to .index().

Example

sentence = "Hello world, welcome to the universe."
# Find the index of "world"
index = sentence.find("world")
print(f"The index of 'world' is: {index}")
# Output: The index of 'world' is: 6
# Find the index of "python", which is not in the string
index_python = sentence.find("python")
print(f"The index of 'python' is: {index_python}")
# Output: The index of 'python' is: -1

You can safely check for -1 to see if the substring was found, which avoids the need for try...except blocks.

Safe Pattern with .find()

my_string = "This is a sample string."
substring_to_find = "sample"
index = my_string.find(substring_to_find)
if index != -1:
    print(f"'{substring_to_find}' was found at index {index}.")
else:
    print(f"'{substring_to_find}' was not found in the string.")
# Output: 'sample' was found at index 10.

Finding All Occurrences (.index() vs. .find())

Neither .index() nor .find() can find all occurrences on their own. To do this, you need to use a loop.

Here is a robust function that uses .find() in a loop to find all starting indices of a substring.

def find_all_occurrences(string, substring):
    """Finds all starting indices of a substring in a string."""
    start = 0
    occurrences = []
    while True:
        # Find the next occurrence starting from 'start'
        index = string.find(substring, start)
        # If find() returns -1, the substring is no longer found
        if index == -1:
            break
        # Add the found index to our list
        occurrences.append(index)
        # Move the start search index past the one we just found
        # to avoid an infinite loop and find the next one.
        start = index + 1
    return occurrences
text = "ababababab"
sub = "ab"
all_indices = find_all_occurrences(text, sub)
print(f"All indices of '{sub}' are: {all_indices}")
# Output: All indices of 'ab' are: [0, 2, 4, 6, 8]

Summary: .index() vs. .find()()

Feature str.index(sub) str.find(sub)
Purpose Find the first index of a substring. Find the first index of a substring.
If Found Returns the starting index (an integer). Returns the starting index (an integer).
If NOT Found Raises a ValueError. Returns -1.
Best For When you expect the substring to always be there, and its absence is a critical error that should crash the program. When the substring might not be there, and you want to handle that case gracefully without crashing.
Recommendation Use with a try...except block if unsure. Generally safer and more convenient for most use cases.

What about the in operator?

If you only need to know if a substring exists (i.e., get a True or False), and not its index, the in operator is the most Pythonic way.

sentence = "Hello world, welcome to the universe."
if "world" in sentence:
    print("Yes, 'world' is in the sentence.")
else:
    print("No, 'world' is not in the sentence.")
# Output: Yes, 'world' is in the sentence.
分享:
扫描分享到社交APP
上一篇
下一篇