How to Match Strings for Case Sensitivity in Python



Python


In this article, we show how to match strings for case sensitivity in Python.

There are times when you want to be able to match strings exactly according to case, meaning the case of the string matters and is important.

We can check this match using the fnmatchcase() function.

This function checks to see if all the cases of a string match up to a certain regular expression where case matters. If it does match up, this function returns true. If all the cases of the strings don't match the regular expression, it returns false.

The fnmatchase() function takes in 2 parameters.

The first parameter is the string you want to match.

The second parameter is the regular expression that we want the string to adhere to.

The fnmatchcase() function checks to see if the string matches the case as what is specified in the regular expression that is used.

So let's go over in code some examples of how this fnmatchcase() function works.



So the first thing we must do is import the fnmatchcase function.

Next, we do a few examples with the fnmatchcase() function.

Again, this function takes in 2 parameters.

The first parameter is the string we want to check.

The second parameter is the regular expression that we want the string to adhere to in terms of what it must match in terms of the strings and also the case.

The regular expression we use for each example is, '*png'.

This regular expression means that the anything can precede the file name, png, but the string must end with 'png' and the fnmatchase() function means that the case of the string must match 'png', which means all the letters must be lowercase (in the png file extension).

In the first example, we have the string, 'nature.png'. Since all the string ends with 'png' with all the characters lowercase, the fnmatchcase() function returns true.

In the second example, the png file extension is all capitalized, so false is returned.

In the third example, the png file extension starts with a capital, so false is returned.

So you can tell that the fnmatchcase() matches the string and the case of the string. Everything has to match the regular expression in order for it to return true.

You can then use this function in something such as an if statement and then execute whatever code you need to.

So, again, this is how we can match strings for case sensitivity using the fnmatchcase() function 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...