What string method returns the lowest index in the string where a specified substring is found?

Returns the index of the first occurrence of the specified substring.

Minimal Example

>>> 'hello world'.find('or') 7

As you read over the explanations below, feel free to watch our video guide about this particular string method:

Python String Methods [Ultimate Guide]

Syntax and Explanation

str.find(sub[, start[, end]])

Returns the index of the first occurrence of the specified substring.

In particular, return the lowest index in the string where sub is found within the slice str[start:end]. You can set the optional arguments start and end as in standard Python slicing.

If it doesn’t find any occurrence of the substring in the original string, it returns -1.

More String Methods

Python’s string class comes with a number of useful additional string methods. Here’s a short collection of all Python string methods—each link opens a short tutorial in a new tab.

MethodDescription
capitalize()Return a copy of the string with capitalized first character and lowercased remaining characters.
casefold()Return a lowercased, casefolded string similar to lowercase() but more aggressive.
center()Return a centered string of a certain length, padded with whitespace or custom characters.
count()Return the number of non-overlapping occurrences of a substring.
encode()Returns a byte object that is an encoded version of the string.
endswith()Returns whether the string ends with a given value or not (True or False).
expandtabs()Return a string with spaces instead of tab characters.
find()Returns the index of the first occurrence of the specified substring.
format()Formats the string according to the Format Description Language.
format_map()Formats the string according to the Format Description Language, passing a mapping object.
index()Returns the index of the first occurrence of the specified substring, like find() but it raises a ValueError if the substring is not found.
isalnum()Checks whether all characters are alphabetic or numeric (True or False).
isalpha()Checks whether all characters are alphabetic (True or False).
isascii()Checks whether all characters are ASCII (True or False).
isdecimal()Checks whether all characters are decimal numbers (True or False).
isdigit()Checks whether all characters are digits, i.e., numbers from 0 to 9 (True or False).
isidentifier()Checks whether all characters are identifiers that can be used as names of functions, classes, or variables (True or False).
islower()Checks whether all characters are lowercase (True or False).
isnumeric()Checks whether all characters are numeric values (True or False).
isprintable()Checks whether all characters are printable (True or False).
isspace()Checks whether all characters are whitespaces (True or False).
istitle()Checks if the string is title-cased (True or False).
isupper()Checks whether all characters are uppercase (True or False).
join()Concatenates the elements in an iterable.
ljust()Returns a left-justified string filling up the right-hand side with fill characters.
lower()Returns a lowercase string version.
lstrip()Trims whitespaces on the left and returns a new string.
maketrans()Returns a translation table.
partition()Searches for a separator substring and returns a tuple with three strings: (1) everything before the separator, (2) the separator itself, and (3) everything after it.
removeprefix()Return string[len(prefix):] if the string starts with prefix, and string[:] otherwise.
removesuffix()Return string[:-len(suffix)] if the string starts with suffix, and string[:] otherwise.
replace()Returns a string with replaced values.
rfind()Return the highest index in the string where a substring is found. Returns -1 if not found.
rindex()Return the highest index in the string where a substring is found. Returns ValueError if not found.
rjust()Returns a right-justified string filling up the left-hand side with fill characters.
rpartition()Searches for a separator substring and returns a tuple with three strings: (1) everything before the separator, (2) the separator itself, and (3) everything after it.
rsplit()Splits the string at a given separator and returns a split list of substrings.
rstrip()Trims whitespaces on the right and returns a new string.
split()Splits the string at a given separator and returns a split list of substrings.
splitlines()Splits the string at line breaks such as '\n' and returns a split list of substrings (i.e., lines).
startswith()Returns whether the string starts with a given value or not (True or False).
strip()Trims whitespaces on the left and right and returns a new string.
swapcase()Swaps lowercase to uppercase characters and vice versa.
title()Returns a new string with uppercase first characters of each word.
translate()Returns a translated string.
upper()Returns a lowercase string version.
zfill()Fills the string from the left with "0" characters.

What string method returns the lowest index in the string where a specified substring is found?

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

The index() method returns the index of the first occurence of a substring in the given string. It is same as the find() method except that if a substring is not found, then it raises an exception.

Syntax:

str.index(substr, start, end)

Parameters:

  1. substr: (Required) The substring whose index has to be found.
  2. start: (Optional) The starting index position from where the searching should start in the string. Default is 0.
  3. end: (Optional) The ending index position untill the searching should happen. Default is end of the string.

Return Value:

An integer value indicating an index of the specified substring.

The following examples demonstrates index() method.

greet='Hello World!' print('Index of H: ', greet.index('H')) print('Index of e: ', greet.index('e')) print('Index of l: ', greet.index('l')) print('Index of World: ', greet.index('World'))

Index of H: 0 Index of e: 1 Index of l: 2 Index of World: 6

The index() method returns an index of the first occurance only.

greet='Hello World' print('Index of l: ', greet.index('l')) print('Index of o: ', greet.index('o'))

Index of l: 2 Index of o: 4

The index() method performs case-sensitive search. It throws ValueError if a substring not found.

greet='Hello World' print(greet.index('h')) # throws error: substring not found print(greet.index('hello')) # throws error

ValueError: substring not found ValueError: substring not found

If a given substring could not be found then it will throw an error.

mystr='TutorialsTeacher is a free online learning website' print(mystr.index('python'))

Traceback (most recent call last) <ipython-input-3-a72aac0824ca> in <module> 1 str='TutorialsTeacher is a free online learning website' ----> 2 print(str.index('python')) ValueError: substring not found

Use start and end parameter to limit the search of a substring between the specified starting and ending index.

mystr='tutorialsteacher is a free tutorials website' print(mystr.index('tutorials',10)) # search starts from 10th index print(mystr.index('tutorials',1, 26)) # throws error; searches between 1st and 26th index

27 ValueError: substring not found