Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. str.find() / str.index() / str.count()

str.find() / str.index() / str.count()

Methods for searching a substring within a string, retrieving its position, or counting its occurrences.

Syntax

# Returns the index of the first occurrence of the substring. Returns -1 if not found.
str.find(sub, start=0, end=len(str))

# Searches from the right (end of the string).
str.rfind(sub, start=0, end=len(str))

# Same as find(), but raises ValueError if the substring is not found.
str.index(sub, start=0, end=len(str))

# Same as index(), but searches from the right.
str.rindex(sub, start=0, end=len(str))

# Returns the number of non-overlapping occurrences of the substring.
str.count(sub, start=0, end=len(str))

Method List

MethodDescription
str.find(sub, start, end)Returns the index of the first occurrence of substring sub. Returns -1 if not found.
str.rfind(sub, start, end)Returns the index of the last occurrence of substring sub (searches from the right). Returns -1 if not found.
str.index(sub, start, end)Same as find(), but raises ValueError instead of returning -1 if not found.
str.rindex(sub, start, end)Same as rfind(), but raises ValueError if not found.
str.count(sub, start, end)Returns the number of non-overlapping occurrences of substring sub. Returns 0 if not found.

Sample Code

# Use find() to locate a substring.
text = "Python is a fun programming language. Let's learn Python."
pos = text.find("Python")
print(pos)  # 0 (position of the first match)

# Searching for a string that doesn't exist returns -1.
print(text.find("Ruby"))  # -1

# Specify a start position to find the second occurrence of "Python".
second_pos = text.find("Python", 1)  # Search from index 1 onward.
print(second_pos)  # Returns the position of the second "Python".

# Use rfind() to search from the right.
print(text.rfind("Python"))  # Returns the position of the last "Python".

# Example of using find() in a conditional.
email = "user@example.com"
if email.find("@") != -1:
    print("Valid email format.")
else:
    print("No @ symbol found.")

# index() raises ValueError if the substring is not found.
try:
    pos2 = text.index("Java")
except ValueError:
    print("Java was not found.")

# Use count() to count occurrences.
message = "I love bananas. Bananas are delicious. Bananas are rich in vitamins."
n = message.count("Bananas")
print(n)  # 2

# Count non-overlapping occurrences.
print("aaaa".count("aa"))  # 2 ("aa" appears twice without overlapping)

# Specify a search range.
text2 = "abcabcabc"
print(text2.count("a", 0, 5))  # Count "a" in the range from index 0 to 4.

# Choosing between find() and the in operator.
# Use in when you only need to check whether a substring is present — it's more concise.
url = "https://example.com"
if "https" in url:
    print("Secure HTTPS connection.")

# Use find() when you need the position.
at_pos = email.find("@")
if at_pos != -1:
    domain = email[at_pos + 1:]  # Everything after @ is the domain.
    print(f"Domain: {domain}")

Notes

The key difference between find() and index() is what happens when the substring is not found. find() returns -1, while index() raises a ValueError exception. When searching for a substring that may not exist, find() is easier to use since it does not require exception handling.

If you only need to check whether a string contains a substring, the in operator is more concise and readable than find(). Use find() only when you also need the index position.

For advanced pattern matching with regular expressions, use the standard library's re module. re.search(pattern, string) returns the position of the first match and handles more complex search conditions. To check whether a string starts or ends with a specific substring, see str.startswith() / str.endswith().

If you find any errors or copyright issues, please .