How to Search for a Case-Insensitive String in Text in Python


In this article, we show how to search for a case-insensitive string in text in Python.

This means that we can look up a string in text in Python and it will return matches regardless of what case the string is in.

Therefore, if we're looking for the string, 'Python' in a text, it will find matches regardless of the case of the string. Therefore, matches it can return include 'PYTHON', 'Python', 'pYthon', pyTHON', etc.

It will return all matches for 'python' regardless of the case of any characters of that string.

So how do we do this?

We can use the re module in Python and use its findall() function.

Within this re.findall(), we add a parameter that makes the function find all matches of the string regardless of the case. This parameter is, flags=re.IGNORECASE

We show this in the code below.

So the first thing we must do is impore the re module. We will be using its findall() function in order to find all matches of the string we are looking for.

Next, we have our full text that we will be searching for particular strings.

Next, we use the re.findall() function in order to all matches of the string we are looking for in text.

The re.findall() function takes in a few parameters.

The first parameter is the string we are looking for. In this case, it is 'python'.

The second parameter is the text where we are looking for this string.

A third optional parameter is to specify whether case for the string matters or not. In this example, we want to find all matches of the string regardless of case. Therefore, we specify, flags=re.IGNORECASE

After running this code, we get all 4 matches of 'python' form the text. You can see that all 4 matches are in different cases ('Python', 'PYTHON', 'PyTHON', 'PythoN').

If we didn't have the third parameter, flags=re.IGNORECASE, in the re.findall() function, the function would return no matches. This is because, by default, the re.findall() function takes into account the case of the string you are searching for. Since 'python' does not appear within the text, there would be no matches. But if you don't care about the case of the text, this wouldn't be the result you would be looking for.

So this is how you can search case-insensitive text in Python.

Related Resources

How to Create a Zip File in Python

How to Extract All Files and Folders from a Zip File in Python

How to Read the Contents of a Zip File in Python

HTML Comment Box is loading comments...