find and index ExamplesΒΆ

The general syntax for these methods is:

string_name.find(a_string)
string_name.index(a_string)

a_string is called a substring, which means that it will match a smaller part of string_name.

Given the value a_string, both find() and index() return the integer index for the first occurrence of a_string in string_name.

The difference between the two methods appears when a_string is NOT found in string_name.

  1. find() returns a value of -1.

  2. index() throws and error, and the program stops running.

Examples

1
2
3
4
5
6
7
8
text = "Rainbow Unicorns"
pets = "dogs and dogs and dogs!"

print(text.find('i'))
print(pets.index('dog'))

print(text.find('Q'))
print(pets.index('cats'))

Console Output

2
0
-1
ValueError, line 8: substring not found

Example

An email address must contain an @ symbol. Checking for this symbol is a part of email verification in most programs.

1
2
3
4
5
6
7
user_input = "[email protected]"
at_index = user_input.find("@")

if at_index > -1:
   print("Email contains @")
else:
   print("Invalid email")

Console Output

Email contains @