← Winnitude! Search  ·  Reader Mode (160 ms)
Links: Stay in Reader Retro Site Converter Retro Mode: OFF Original Page ↗
PYTHONREAD.GITHUB.IO · learnPython · 2 LINKS

String find() in Python - Python Tutorial

The find(query) method is built-in to standard python. Just call the method on the string object to search for a string, like so: obj.find('search') .

The find() method searches for a query string and returns the character position if found. If the string is not found, it returns -1.

In simple English: find out if a string contains another string.

Related course: Complete Python Programming Course & Exercises

Example

Find method

The find method returns the index if a word is found. If not found, it returns -1. You can add a starting index and end index: find(query, start, end) , but these parameters are optional.

Try the program below:

1

2
3
4
s = "That I ever did see. Dusty as the handle on the door"


index = s.find("Dusty")
print(index)

Save the program as search.py, run from terminal or IDE.
You should see this output:

The in keyword

You can also use the keyword _in_. The example below shows you how to use the Python in keyword.

1

2
3
4
s = "That I ever did see. Dusty as the handle on the door"


if "Dusty" in s:
print("query found")

The difference is the in keyword returns if the string contains a word, but find returns the character position.

If you are a beginner, then I highly recommend this YouTube Python Playlist.

Exercise

Try the exercises below

  1. Find out if string find is case sensitive
  2. What if a query string appers twice in the string?
  3. Write a program that asks console input and searches for a query.