Поиск слова в строке Python
Как написать условие которое будет искать слово в строке?
Пользователь вводит какую-то строку, например:
Тогда Python проверяет, если в вводимой строке есть слово «звать» — тогда вывести print(«Привет») .
Я делаю так, но не работает так как нужно:
Если я введу «меня звать. » то ничего не произойдет
Если введу просто слово «звать» — то напишет «Привет»
![]()
Используйте регулярные выражения.
Он сравнивает целую строку с условием «звать» соответственно «звать» <> «меня звать» Я не чего не смыслю в питоне, я больше по sql. Но немного загуглив нашел, у вас должно быть так. find метод поиска в строке ,возвращает индекс первого вхождения подстроки в строку, в случае отсутствия подстроки ,возвращает -1. Имеет вид str1.find(str2,[start],[end])
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!
How to Check if a Python String Contains a Substring
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Check if a Python String Contains a Substring
If you’re new to programming or come from a programming language other than Python, you may be looking for the best way to check whether a string contains another string in Python.
Identifying such substrings comes in handy when you’re working with text content from a file or after you’ve received user input. You may want to perform different actions in your program depending on whether a substring is present or not.
In this tutorial, you’ll focus on the most Pythonic way to tackle this task, using the membership operator in . Additionally, you’ll learn how to identify the right string methods for related, but different, use cases.
Finally, you’ll also learn how to find substrings in pandas columns. This is helpful if you need to search through data from a CSV file. You could use the approach that you’ll learn in the next section, but if you’re working with tabular data, it’s best to load the data into a pandas DataFrame and search for substrings in pandas.
Free Download: Click here to download the sample code that you’ll use to check if a string contains a substring.
How to Confirm That a Python String Contains Another String
If you need to check whether a string contains a substring, use Python’s membership operator in . In Python, this is the recommended way to confirm the existence of a substring in a string:
The in membership operator gives you a quick and readable way to check whether a substring is present in a string. You may notice that the line of code almost reads like English.
Note: If you want to check whether the substring is not in the string, then you can use not in :
Because the substring «secret» is present in raw_file_content , the not in operator returns False .
When you use in , the expression returns a Boolean value:
- True if Python found the substring
- False if Python didn’t find the substring
You can use this intuitive syntax in conditional statements to make decisions in your code:
In this code snippet, you use the membership operator to check whether «secret» is a substring of raw_file_content . If it is, then you’ll print a message to the terminal. Any indented code will only execute if the Python string that you’re checking contains the substring that you provide.
Note: Python considers empty strings always as a substring of any other string, so checking for the empty string in a string returns True :
This may be surprising because Python considers emtpy strings as false, but it’s an edge case that is helpful to keep in mind.
The membership operator in is your best friend if you just need to check whether a Python string contains a substring.
However, what if you want to know more about the substring? If you read through the text stored in raw_file_content , then you’ll notice that the substring occurs more than once, and even in different variations!
Which of these occurrences did Python find? Does capitalization make a difference? How often does the substring show up in the text? And what’s the location of these substrings? If you need the answer to any of these questions, then keep on reading.
Generalize Your Check by Removing Case Sensitivity
Python strings are case sensitive. If the substring that you provide uses different capitalization than the same word in your text, then Python won’t find it. For example, if you check for the lowercase word «secret» on a title-case version of the original text, the membership operator check returns False :
Despite the fact that the word secret appears multiple times in the title-case text title_cased_file_content , it never shows up in all lowercase. That’s why the check that you perform with the membership operator returns False . Python can’t find the all-lowercase string «secret» in the provided text.
Humans have a different approach to language than computers do. This is why you’ll often want to disregard capitalization when you check whether a string contains a substring in Python.
You can generalize your substring check by converting the whole input text to lowercase:
Converting your input text to lowercase is a common way to account for the fact that humans think of words that only differ in capitalization as the same word, while computers don’t.
Note: For the following examples, you’ll keep working with file_content , the lowercase version of your text.
If you work with the original string ( raw_file_content ) or the one in title case ( title_cased_file_content ), then you’ll get different results because they aren’t in lowercase. Feel free to give that a try while you work through the examples!
Now that you’ve converted the string to lowercase to avoid unintended issues stemming from case sensitivity, it’s time to dig further and learn more about the substring.
Learn More About the Substring
The membership operator in is a great way to descriptively check whether there’s a substring in a string, but it doesn’t give you any more information than that. It’s perfect for conditional checks—but what if you need to know more about the substrings?
Python provides many additonal string methods that allow you to check how many target substrings the string contains, to search for substrings according to elaborate conditions, or to locate the index of the substring in your text.
In this section, you’ll cover some additional string methods that can help you learn more about the substring.
Note: You may have seen the following methods used to check whether a string contains a substring. This is possible—but they aren’t meant to be used for that!
Programming is a creative activity, and you can always find different ways to accomplish the same task. However, for your code’s readability, it’s best to use methods as they were intended in the language that you’re working with.
By using in , you confirmed that the string contains the substring. But you didn’t get any information on where the substring is located.
If you need to know where in your string the substring occurs, then you can use .index() on the string object:
When you call .index() on the string and pass it the substring as an argument, you get the index position of the first character of the first occurrence of the substring.
Note: If Python can’t find the substring, then .index() raises a ValueError exception.
But what if you want to find other occurrences of the substring? The .index() method also takes a second argument that can define at which index position to start looking. By passing specific index positions, you can therefore skip over occurrences of the substring that you’ve already identified:
When you pass a starting index that’s past the first occurrence of the substring, then Python searches starting from there. In this case, you get another match and not a ValueError .
That means that the text contains the substring more than once. But how often is it in there?
You can use .count() to get your answer quickly using descriptive and idiomatic Python code:
You used .count() on the lowercase string and passed the substring «secret» as an argument. Python counted how often the substring appears in the string and returned the answer. The text contains the substring four times. But what do these substrings look like?
You can inspect all the substrings by splitting your text at default word borders and printing the words to your terminal using a for loop:
In this example, you use .split() to separate the text at whitespaces into strings, which Python packs into a list. Then you iterate over this list and use in on each of these strings to see whether it contains the substring «secret» .
Note: Instead of printing the substrings, you could also save them in a new list, for example by using a list comprehension with a conditional expression:
In this case, you build a list from only the words that contain the substring, which essentially filters the text.
Now that you can inspect all the substrings that Python identifies, you may notice that Python doesn’t care whether there are any characters after the substring «secret» or not. It finds the word whether it’s followed by whitespace or punctuation. It even finds words such as «secretly» .
That’s good to know, but what can you do if you want to place stricter conditions on your substring check?
Find a Substring With Conditions Using Regex
You may only want to match occurrences of your substring followed by punctuation, or identify words that contain the substring plus other letters, such as «secretly» .
For such cases that require more involved string matching, you can use regular expressions, or regex, with Python’s re module.
For example, if you want to find all the words that start with «secret» but are then followed by at least one additional letter, then you can use the regex word character ( \w ) followed by the plus quantifier ( + ):
The re.search() function returns both the substring that matched the condition as well as its start and end index positions—rather than just True !
You can then access these attributes through methods on the Match object, which is denoted by m :
These results give you a lot of flexibility to continue working with the matched substring.
For example, you could search for only the substrings that are followed by a comma ( , ) or a period ( . ):
There are two potential matches in your text, but you only matched the first result fitting your query. When you use re.search() , Python again finds only the first match. What if you wanted all the mentions of «secret» that fit a certain condition?
To find all the matches using re , you can work with re.findall() :
By using re.findall() , you can find all the matches of the pattern in your text. Python saves all the matches as strings in a list for you.
When you use a capturing group, you can specify which part of the match you want to keep in your list by wrapping that part in parentheses:
By wrapping secret in parentheses, you defined a single capturing group. The findall() function returns a list of strings matching that capturing group, as long as there’s exactly one capturing group in the pattern. By adding the parentheses around secret, you managed to get rid of the punctuation!
Note: Remember that there were four occurrences of the substring «secret» in your text, and by using re , you filtered out two specific occurrences that you matched according to special conditions.
Using re.findall() with match groups is a powerful way to extract substrings from your text. But you only get a list of strings, which means that you’ve lost the index positions that you had access to when you were using re.search() .
If you want to keep that information around, then re can give you all the matches in an iterator:
When you use re.finditer() and pass it a search pattern and your text content as arguments, you can access each Match object that contains the substring, as well as its start and end index positions.
You may notice that the punctuation shows up in these results even though you’re still using the capturing group. That’s because the string representation of a Match object displays the whole match rather than just the first capturing group.
But the Match object is a powerful container of information and, like you’ve seen earlier, you can pick out just the information that you need:
By calling .group() and specifying that you want the first capturing group, you picked the word secret without the punctuation from each matched substring.
You can go into much more detail with your substring matching when you use regular expressions. Instead of just checking whether a string contains another string, you can search for substrings according to elaborate conditions.
Note: If you want to learn more about using capturing groups and composing more complex regex patterns, then you can dig deeper into regular expressions in Python.
Using regular expressions with re is a good approach if you need information about the substrings, or if you need to continue working with them after you’ve found them in the text. But what if you’re working with tabular data? For that, you’ll turn to pandas.
Find a Substring in a pandas DataFrame Column
If you work with data that doesn’t come from a plain text file or from user input, but from a CSV file or an Excel sheet, then you could use the same approach as discussed above.
However, there’s a better way to identify which cells in a column contain a substring: you’ll use pandas! In this example, you’ll work with a CSV file that contains fake company names and slogans. You can download the file below if you want to work along:
Free Download: Click here to download the sample code that you’ll use to check if a string contains a substring.
When you’re working with tabular data in Python, it’s usually best to load it into a pandas DataFrame first:
In this code block, you loaded a CSV file that contains one thousand rows of fake company data into a pandas DataFrame and inspected the first five rows using .head() .
Note: You’ll need to create a virtual environment and install pandas in order to work with the library.
After you’ve loaded the data into the DataFrame, you can quickly query the whole pandas column to filter for entries that contain a substring:
You can use .str.contains() on a pandas column and pass it the substring as an argument to filter for rows that contain the substring.
Note: The indexing operator ( [] ) and attribute operator ( . ) offer intuitive ways of getting a single column or slice of a DataFrame.
However, if you’re working with production code that’s concerned with performance, pandas recommends using the optimized data access methods for indexing and selecting data.
When you’re working with .str.contains() and you need more complex match scenarios, you can also use regular expressions! You just need to pass a regex-compliant search pattern as the substring argument:
In this code snippet, you’ve used the same pattern that you used earlier to match only words that contain secret but then continue with one or more word character ( \w+ ). Only one of the companies in this fake dataset seems to operate secretly!
You can write any complex regex pattern and pass it to .str.contains() to carve from your pandas column just the rows that you need for your analysis.
Conclusion
Like a persistent treasure hunter, you found each «secret» , no matter how well it was hidden! In the process, you learned that the best way to check whether a string contains a substring in Python is to use the in membership operator.
You also learned how to descriptively use two other string methods, which are often misused to check for substrings:
- .count() to count the occurrences of a substring in a string
- .index() to get the index position of the beginning of the substring
After that, you explored how to find substrings according to more advanced conditions with regular expressions and a few functions in Python’s re module.
Finally, you also learned how you can use the DataFrame method .str.contains() to check which entries in a pandas DataFrame contain a substring .
You now know how to pick the most idiomatic approach when you’re working with substrings in Python. Keep using the most descriptive method for the job, and you’ll write code that’s delightful to read and quick for others to understand.
Free Download: Click here to download the sample code that you’ll use to check if a string contains a substring.
Take the Quiz: Test your knowledge with our interactive “How to Check if a Python String Contains a Substring” quiz. Upon completion you will receive a score so you can track your learning progress over time:
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Check if a Python String Contains a Substring
Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

About Martin Breuss
Martin likes automation, goofy jokes, and snakes, all of which fit into the Python community. He enjoys learning and exploring and is up for talking about it, too. He writes and records content for Real Python and CodingNomads.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:




Master Real-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Master Real-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!
Python Search for a String in Text Files
In this Python tutorial, you’ll learn to search a string in a text file. Also, we’ll see how to search a string in a file and print its line and line number.
After reading this article, you’ll learn the following cases.
- If a file is small, read it into a string and use the find() method to check if a string or word is present in a file. (easier and faster than reading and checking line per line)
- If a file is large, use the mmap to search a string in a file. We don’t need to read the whole file in memory, which will make our solution memory efficient.
- Search a string in multiple files
- Search file for a list of strings
We will see each solution one by one.
Table of contents
How to Search for a String in Text File
Use the file read() method and string class find() method to search for a string in a text file. Here are the steps.
-
Open file in a read mode
Open a file by setting a file path and access mode to the open() function. The access mode specifies the operation you wanted to perform on the file, such as reading or writing. For example, r is for reading. fp= open(r’file_path’, ‘r’)
Once opened, read all content of a file using the read() method. The read() method returns the entire file content in string format.
Use the find() method of a str class to check the given string or word present in the result returned by the read() method. The find() method. The find() method will return -1 if the given text is not present in a file
If you need line and line numbers, use the readlines( ) method instead of read() method. Use the for loop and readlines() method to iterate each line from a file. Next, In each iteration of a loop, use the if condition to check if a string is present in a current line and print the current line and line number
Example to search for a string in text file
I have a ‘sales.txt’ file that contains monthly sales data of items. I want the sales data of a specific item. Let’s see how to search particular item data in a sales file.

Output:
Search file for a string and Print its line and line number
Use the following steps if you are searching a particular text or a word in a file, and you want to print a line number and line in which it is present.
- Open a file in a read mode.
- Next, use the readlines() method to get all lines from a file in the form of a list object.
- Next, use a loop to iterate each line from a file.
- Next, In each iteration of a loop, use the if condition to check if a string is present in a current line and print the current line and line number.
Example: In this example, we’ll search the string ‘laptop’ in a file, print its line along with the line number.
Output:
Note: You can also use the readline() method instead of readlines() to read a file line by line, stop when you’ve gotten to the lines you want. Using this technique, we don’t need to read the entire file.
Efficient way to search string in a large text file
All above way read the entire file in memory. If the file is large, reading the whole file in memory is not ideal.
In this section, we’ll see the fastest and most memory-efficient way to search a string in a large text file.
- Open a file in read mode
- Use for loop with enumerate() function to get a line and its number. The enumerate() function adds a counter to an iterable and returns it in enumerate object. Pass the file pointer returned by the open() function to the enumerate() .
- We can use this enumerate object with a for loop to access the each line and line number.
Note: The enumerate(file_pointer) doesn’t load the entire file in memory, so this is an efficient solution.
Example:
Example:
mmap to search for a string in text file
In this section, we’ll see the fastest and most memory-efficient way to search a string in a large text file.
Also, you can use the mmap module to find a string in a huge file. The mmap.mmap() method creates a bytearray object that checks the underlying file instead of reading the whole file in memory.
Example:
Output:
Search string in multiple files
Sometimes you want to search a string in multiple files present in a directory. Use the below steps to search a text in all files of a directory.
Example:
Output:
Search file for a list of strings
Sometimes you want to search a file for multiple strings. The below example shows how to search a text file for any words in a list.
Example:
Output:
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.