Python find() – How to Search for a Substring in a String
Dionysia Lemonaki

When you’re working with a Python program, you might need to search for and locate a specific string inside another string.
This is where Python’s built-in string methods come in handy.
In this article, you will learn how to use Python’s built-in find() string method to help you search for a substring inside a string.
Here is what we will cover:
The find() Method — A Syntax Overview
The find() string method is built into Python’s standard library.
It takes a substring as input and finds its index — that is, the position of the substring inside the string you call the method on.
The general syntax for the find() method looks something like this:
Let’s break it down:
- string_object is the original string you are working with and the string you will call the find() method on. This could be any word you want to search through.
- The find() method takes three parameters – one required and two optional.
- «substring» is the first required parameter. This is the substring you are trying to find inside string_object . Make sure to include quotation marks.
- start_index_number is the second parameter and it’s optional. It specifies the starting index and the position from which the search will start. The default value is 0 .
- end_index_number is the third parameter and it’s also optional. It specifies the end index and where the search will stop. The default is the length of the string.
- Both the start_index_number and the end_index_number specify the range over which the search will take place and they narrow the search down to a particular section.
The return value of the find() method is an integer value.
If the substring is present in the string, find() returns the index, or the character position, of the first occurrence of the specified substring from that given string.
If the substring you are searching for is not present in the string, then find() will return -1 . It will not throw an exception.
How to Use find() with No Start and End Parameters Example
The following examples illustrate how to use the find() method using the only required parameter – the substring you want to search.
You can take a single word and search to find the index number of a specific letter:
I created a variable named fave_phrase and stored the string Hello world! .
I called the find() method on the variable containing the string and searched for the letter ‘w’ inside Hello world! .
I stored the result of the operation in a variable named search_fave_phrase and then printed its contents to the console.
The return value was the index of w which in this case was the integer 6 .
Keep in mind that indexing in programming and Computer Science in general always starts at 0 and not 1 .
How to Use find() with Start and End Parameters Example
Using the start and end parameters with the find() method lets you limit your search.
For example, if you wanted to find the index of the letter ‘w’ and start the search from position 3 and not earlier, you would do the following:
Since the search starts at position 3, the return value will be the first instance of the string containing ‘w’ from that position and onwards.
You can also narrow down the search even more and be more specific with your search with the end parameter:
Substring Not Found Example
As mentioned earlier, if the substring you specify with find() is not present in the string, then the output will be -1 and not an exception.
Is the find() Method Case-Sensitive?
What happens if you search for a letter in a different case?
In an earlier example, I searched for the index of the letter w in the phrase «Hello world!» and the find() method returned its position.
In this case, searching for the letter W capitalized returns -1 – meaning the letter is not present in the string.
So, when searching for a substring with the find() method, remember that the search will be case-sensitive.
The find() Method vs the in Keyword – What’s the Difference?
Use the in keyword to check if the substring is present in the string in the first place.
The general syntax for the in keyword is the following:
The in keyword returns a Boolean value – a value that is either True or False .
The in operator returns True when the substring is present in the string.
And if the substring is not present, it returns False :
Using the in keyword is a helpful first step before using the find() method.
You first check to see if a string contains a substring, and then you can use find() to find the position of the substring. That way, you know for sure that the substring is present.
So, use find() to find the index position of a substring inside a string and not to look if the substring is present in the string.
The find() Method vs the index() Method – What’s the Difference?
Similar to the find() method, the index() method is a string method used for finding the index of a substring inside a string.
So, both methods work in the same way.
The difference between the two methods is that the index() method raises an exception when the substring is not present in the string, in contrast to the find() method that returns the -1 value.
The example above shows that index() throws a ValueError when the substring is not present.
You may want to use find() over index() when you don’t want to deal with catching and handling any exceptions in your programs.
Conclusion
And there you have it! You now know how to search for a substring in a string using the find() method.
I hope you found this tutorial helpful.
To learn more about the Python programming language, check out freeCodeCamp’s Python certification.
You’ll start from the basics and learn in an interactive and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce your understanding of the concepts you learned.
Word Search in Python

This implementation of Word Search was, in most part, an experiment—to observe how I utilize Python to try and solve the problem of implementing a basic word search solving algorithm.
Table of contents
What is Word Search?
Word search is a puzzle we usually see in newspapers, and in some magazines, located along the crossword puzzles. They can be located sometimes in bookstores, around the trivia area, as a standalone puzzle book, in which the sole content is a grid of characters and a set of words per page.
How a traditional word search puzzle works is, for a given grid of different characters, you have to find the hidden words inside the grid. The word could be oriented vertically, horizontally, diagonally, and also inversely in the previously mentioned directions. After all the words are found, the remaining letters of the grid expose a secret message.
In some word search puzzles, a limitation exists in the length of the hidden words, in that it should contain more than 2 characters, and the grid should have a fixed size of 10 × 10, or an equivalent length and width proportion (which this python implementation doesn’t have).
How and where do we start?
Before going deeper into the computer side of the algorithm, let’s first clarify how we tend to solve a word search puzzle:
- We look at a hidden word and its first letter then we proceed to look for the first letter inside the grid of letters.
- Once we successfully find the first letter of the hidden word inside the grid, we then check the neighboring characters of that successful match and check whether the second letter of our word matches any of the neighbors of the successful match.
- After confirming a successful match for the second letter of the hidden word through its neighbors, we proceed to a much narrower step. After the successful matching of the second letter of the word in the successful second match’s neighbors, we then follow-through to a straight line from there, hoping to get a third match (and so on) of the hidden word’s letters.
Which tool do we use?
To realize this series of steps in solving a word search puzzle, we will utilize a programming language known for having a syntax similar to pseudo-code—Python.
There are two main versions of Python—versions 2.x and 3.x. For this project, we would be utilizing version 2.7.
To make this run under Python 3.X, replace all instances of xrange with range .
Python installation
For the installation part, we’ll be covering installation instructions for both Windows, Unix, and Linux.
Windows
First, determine whether you’re running a 32- or 64-bit operating system. To do that, click Start, right-click Computer, then click Properties. You should see whether you’re running on 32-bit or 64-bit under System type. If you’re running on 32-bit, click on this link then start the download; if you’re on 64-bit, click this one. Again, take note that we will be utilizing version 2.7 of Python.
Linux and Unix
Download this file then extract. After extraction, go inside the extracted directory then run the following:
In Linux/Unix, to make sure that we can actually run Python when we enter the python command in a terminal, let’s make sure that the installed Python files can be located by the system.
Type the following, then press Enter on your corresponding shell:
Bash, Sh, Zsh, Ash, or Ksh:
Pen and paper
As problems go in software development or in programming in general, it is better to tackle the problem with a clear head—going at it with the problem statement and constraints clear in our minds. What we are going to do first is to outline the initial crucial steps in a word search puzzle.
First, write the word dog , then on the space immediately below it, draw a grid of characters on the paper, like the following:
To start the hunt, we look at the first letter of the word dog , which is the letter d . If, somehow, the first letter of dog doesn’t exist within the grid, it means that we won’t be able to find the word in it! If we successfully find a character match for the first letter of dog , we then proceed to look at the second letter of dog . This time, we are now restricted to look around among the adjacent letters of the first letter match. If the second letter of dog can’t be located around the adjacent letters of d inside the grid, this means that we have to proceed to the next occurrence of the letter d inside the grid.
If we find a successful match around the adjacent letters of the next occurrence of d inside the grid, then the next steps are literally straightforward. For example:
In the previous grid, the first letter d matched on the corner of the grid, and the word’s second letter o which is adjacent to d , also successfully matched. If that’s the case, the next location in the grid to check for the subsequent matches of the remaining letters of the word dog , will now be in a straight line with the direction drawn from the first letter to the second letter. In this case, we will check the letter directly above o for the third letter of the word dog , which is g . If instead of the asterisk, the grid showed:
This means that we don’t have a match, and we should be going to the next occurrence of the first letter, inside the grid. If the asterisk is replaced by the correct missing letter:
We have a match! However, for our version of word search, we will not stop there. Instead, we will count for all the adjacent letters of the letter d , then look for the matches of the letter o ! For example, if we are presented with the following grid:
Then so far, for the word dog , we found 2 matches! After all the neighbors of the letter d have been checked for a possible match, we then move to the next occurrence of the letter in the grid.
Onto the code!
With the basic algorithm in mind, we can now start implementing the algorithm from the previous section.
Implementing the algorithm
matrixify
The purpose of this function is to return a list whose elements are lines of string. This provides us the ability to index individual elements of the grid through accessing them by their row and column indices:
coord_char
Given a coordinate ((row_index, column_index) structure) and the matrix where this coordinate is supposedly located in, this function returns the element located at that row and column:
convert_to_word
This function will run through a list of coordinates through a for loop and gets the single length strings using coord_char :
and then uses the join() method of strings to return one single string. The » before the join() method is the separator to use in between the strings, but in our case, we want one single word so we used an empty string separator.
find_base_match
The value of base_matches above is computed by a list comprehension . A list comprehension is just another way of constructing a list, albeit a more concise one. The above list comprehension is roughly equivalent to the following:
I used the enumerate() function because it appends a counter to an iterable, and that is handy because the counter’s value could correspond to either the row or column indices of the matrix!
To show that the above code indeed scrolls through the individual characters of grid , let’s modify the body of our for loop in order to display the characters and their corresponding coordinates:
Giving our function find_base_match the arguments d and grid , respectively, we get the following:
As you can see from the previous for loop output, the coordinates output by our function are indeed the coordinates where the character d matched!
By calling this function, we can determine whether or not to continue with the further steps. If we deliberately give find_base_match a character that is not inside grid , like c :
The function returns an empty list! This means, that inside the encompassing function that will call find_base_match , one of the conditions could be:
matched_neighbors
This function finds the adjacent coordinates of the given coordinate, wherein the character of that adjacent coordinate matches the char argument!
Inside neighbors_coords , we’re trying to create a list of all the coordinates adjacent the one we gave, but with some conditions to further filter the resulting coordinate:
In the above code snippet, we are creating a list of adjacent coordinates (through (row, column) ). Because we want to get the immediate neighbors of a certain coordinate, we deduct 1 from our starting range then add 2 to our end range, so that, if given a row of 0, we will be iterating through xrange(-1, 2) . Remember that the range() and xrange() functions is not inclusive of the end range, which means that it doesn’t include the end range in the iteration (hence, the 2 that we add at the end range, not only 1):
We do the same to the column variable, then later, we filter the contents of the final list through an if clause inside the list comprehension. We do that because we don’t want this function to return coordinates that are out of bounds of the matrix.
To further hit the nail in the coffin, we also give this function a character as its second argument. That is because we want to further filter the resulting coordinate. We only want a coordinate whose string equivalent matches the second character argument that we give the function!
If we want to get the neighbors of the coordinate (0, 0) , whose adjacent character in the matrix should be c , call this function with (0, 0) as the first argument, the string c as the second, the matrix itself, and the matrix’s row length and column length, respectively:
Notice that it returns an empty list, because in the neighbors of the coordinate (0, 0) , there is no coordinate in there that has the string c as its string equivalent!
If we replace c with a :
This function returns a list of the adjacent coordinates that match the given character.
complete_line
We are now at the stage where functions seem a bit hairier to comprehend! I will attempt to discuss the thoughts I had before creating this function.
In the Pen and paper section, after matching the first and second letters of the word inside the matrix, I mentioned that the next matching steps become narrower. It becomes narrower in the sense that, after matching the first and second letters of the word, the only thing you need to do after that is to go straight in the direction that the first and second letters created.
In the above grid, once the letters d and o are found, one only need to go straight in a line from the first letter d to the second letter o , then take the direction that d took to get to o . In this case, we go upwards of o to check for the third letter match:
The direction that the above matches create is north-east. This means that we have to check the place north-east of ‘o’:
With that being said, I wanted a function to give me all the coordinates forming a straight line, when given two coordinates.
The first problem I had to solve was—Given two coordinates, how do I compute the coordinate of the third one, which will later form a straight line in the matrix?
To solve this problem, I tried plotting all the expected goal coordinates, if for example, the first coordinate match is (1, 1) and the second coordinate match is (0, 0) :
While looking at the above plot, an idea came into my mind. What I wanted to get was the amount of step needed to go from the second coordinate to the third. In hopes of achieving that, I tried subtracting the row and column values of the first from the second:
After that, I tried adding the values of the diff row to the values of second :
If you look closely, the values of the sum row match those of the expected row! To summarize, I get the difference by subtracting values of the first coordinate from the values of the second coordinate, then I add the difference to the second coordinate to arrive at the expected third!
Now, back to the function:
For this function, I passed the length of the word as an argument for two main reasons—to check for words with a length of two, and for the length of the final list output. We check for double length words because with words that have lengths of 2, we no longer need to compute for a third coordinate because the word only needs two coordinates to be complete.
For the second reason, this serves as the quirk of my algorithm. Instead of checking the third coordinate for a match of the third character (and the subsequent ones), I instead create a list of coordinates, forming a straight line in the matrix, whose length is equal to the length of the word.
I first create the line variable which already contains the coordinates of the first match and the second match of the word. After that, I get the difference of the second coordinates values and the first. Finally, I create a for loop whose loop count is the length of the word minus 2 (because line already has two values inside). Inside the loop, I append to the line list variable a new coordinate by getting line ’s last variable values then adding the difference of the second and first match coordinates.
Finally, to make sure that the created coordinate list can be found inside the matrix, I check the last coordinate of the line variable if it’s within the bounds of the matrix. If it is, I return the newly created coordinate list, and if not, I simply return an empty list.
Let’s say we want a complete line when given coordinate matches (0, 0) and (1, 1) , and the length of our word is 3:
If we give the function a word length of 4:
it returns an empty list because the last coordinate of the created list went out of bounds.
complete_match
This is the complete_line function on steroids. The goal of this function is to apply complete_line to all the neighbors of the first match. After that, it creates a lists of coordinates whose word equivalent is the same as the word we’re trying to look for inside the matrix.
For the value of the new variable, I utilize a generator comprehension. These are like list comprehensions, except, they release their values one by one, only upon request, in contrast to list comprehensions which return all the contents of the list in one go.
To accomplish the application of complete_line to all the neighbors of the first match, I iterate through all the first matches:
then inside that for loop, I iterate through all the neighbors that matched_neighbors gave us:
I then put the following statement in the first part of the generator comprehension:
The above generator comprehension is roughly equivalent to:
After the creation of the new variable, we now start going through its values one by one:
This list comprehension above will filter the new and the resulting list will only contain coordinates that, when converted to its word counterpart, match the original word we wanted to find.
Attempting to find the word dog inside our matrix returns a list of lists containing matched coordinates:
find_matches
This function will serve as the helper of our main function. Its goal is to output a list containing the coordinates of all the possible matches of word inside grid . For general purposes, I defined four variables:
- The word_len variable whose value is the length of the word argument, which will generally be useful throughout the script
- The matrix variable whose value we get through giving grid to our matrixify function, which will allow us to later be able to index contents of the matrix through its row and column indices.
- The row_len and the column_len variable of matrix
- base_matches which contain the coordinates of all the first letter matches of word
After the variables, we will do some sanity checks:
The above if elif statement will check if the length of word is longer than both the column_len and row_len and also checks if base_matches returns an empty list. If that condition is not satisfied, it means that word can fit inside the matrix, and base_matches found a match! However, if the length of word is 1, we simply return base_matches .
If the word is longer than 1, we then pass the local variables to complete_match for further processing.
Given dog , the string chain dogg oogo gogd , and the ‘ ‘ separator as arguments:
Voila! This is the list, which contain lists of coordinates where the word dog matched inside dogg oogo gogd !
wordsearch
This function simply returns the number of matches of running
There are 4 matches of dog inside dogg oogo gogd !
Closing remarks
Remember, it’s never a bad idea to go back to using pen and paper to solve programming problems. Sometimes, we express ideas better using our bare hands, and to top it off, a good ol’ break from the monitor and from the walls of code could just be what you need for a breakthrough—just like when I got stuck thinking about how I should implement my complete_line function!
Как найти слово в строке python
Рассмотрим основные методы строк, которые мы можем применить в приложениях:
isalpha() : возвращает True, если строка состоит только из алфавитных символов
islower() : возвращает True, если строка состоит только из символов в нижнем регистре
isupper() : возвращает True, если все символы строки в верхнем регистре
isdigit() : возвращает True, если все символы строки — цифры
isnumeric() : возвращает True, если строка представляет собой число
startswith(str) : возвращает True, если строка начинается с подстроки str
endswith(str) : возвращает True, если строка заканчивается на подстроку str
lower() : переводит строку в нижний регистр
upper() : переводит строку в вехний регистр
title() : начальные символы всех слов в строке переводятся в верхний регистр
capitalize() : переводит в верхний регистр первую букву только самого первого слова строки
lstrip() : удаляет начальные пробелы из строки
rstrip() : удаляет конечные пробелы из строки
strip() : удаляет начальные и конечные пробелы из строки
ljust(width) : если длина строки меньше параметра width, то справа от строки добавляются пробелы, чтобы дополнить значение width, а сама строка выравнивается по левому краю
rjust(width) : если длина строки меньше параметра width, то слева от строки добавляются пробелы, чтобы дополнить значение width, а сама строка выравнивается по правому краю
center(width) : если длина строки меньше параметра width, то слева и справа от строки равномерно добавляются пробелы, чтобы дополнить значение width, а сама строка выравнивается по центру
find(str[, start [, end]) : возвращает индекс подстроки в строке. Если подстрока не найдена, возвращается число -1
replace(old, new[, num]) : заменяет в строке одну подстроку на другую
split([delimeter[, num]]) : разбивает строку на подстроки в зависимости от разделителя
partition(delimeter) : разбивает строку по разделителю на три подстроки и возвращает кортеж из трех элементов — подстрока до разделителя, разделитель и подстрока после разделителя
join(strs) : объединяет строки в одну строку, вставляя между ними определенный разделитель
Например, если мы ожидаем ввод с клавиатуры числа, то перед преобразованием введенной строки в число можно проверить, с помощью метода isnumeric() введено ли в действительности число, и если так, то выполнить операцию преобразования:
Проверка, начинается или оканчивается строка на определенную подстроку:
Удаление пробелов в начале и в конце строки:
Дополнение строки пробелами и выравнивание:
Поиск в строке
Для поиска подстроки в строке в Python применяется метод find() , который возвращает индекс первого вхождения подстроки в строку и имеет три формы:
find(str) : поиск подстроки str ведется с начала строки до ее конца
find(str, start) : параметр start задает начальный индекс, с которого будет производиться поиск
find(str, start, end) : параметр end задает конечный индекс, до которого будет идти поиск
Если подстрока не найдена, метод возвращает -1:
Замена в строке
Для замены в строке одной подстроки на другую применяется метод replace() :
replace(old, new) : заменяет подстроку old на new
replace(old, new, num) : параметр num указывает, сколько вхождений подстроки old надо заменить на new. По умолчанию num равно -1, что соответствует первой версии метода и приводит к замене всех вхождений.
Разделение на подстроки
Метод split() разбивает строку на список подстрок в зависимости от разделителя. В качестве разделителя может выступать любой символ или последовательность символов. Данный метод имеет следующие формы:
split() : в качестве разделителя используется пробел
split(delimeter) : в качестве разделителя используется delimeter
split(delimeter, num) : параметр num указывает, сколько вхождений delimeter используется для разделения. Оставшаяся часть строки добавляется в список без разделения на подстроки
Еще один метод — partition() разбивает строку по разделителю на три подстроки и возвращает кортеж из трех элементов — подстрока до разделителя, разделитель и подстрока после разделителя:
Если разделитель с строке не найден, то возвращается кортеж с одной строкой.
Соединение строк
При рассмотрении простейших операций со строками было показано, как объединять строки с помощью операции сложения. Другую возможность для соединения строк представляет метод join() : он объединяет список строк. Причем текущая строка, у которой вызывается данный метод, используется в качестве разделителя:
Вместо списка в метод join можно передать простую строку, тогда разделитель будет вставляться между символами этой строки:
Поиск подстроки в строке
Нужно найти в строке: входит ли данная строчка в строку или нет. например, есть строка sdfssf sddff svvsef xbsdf sdfwwe нужно узнать входит ли в нее dff или нет.
![]()
Если что — S.count(str) — это функция, которая считает количество вхождений str в S
Можно с помощью множеств, например при чтении с файла пропускать строки, в которые входит определенное слово:
line_1 — слово которое ищешь. line_2 — где ищешь. 100 — это вероятное совпадения.
Может кому поможет, мою проблему решил.
![]()
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.3.11.43304
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.