Python : How to Compare Strings ? | Ignore case | regex | is vs == operator

In this article we will discuss different ways to compare strings in python like, using == operator (with or without ignoring case) or
using is operator or using regex.

Python provides various operators to compare strings i.e. +, !=, <, >, <=, >=. When used for comparison these operators return Boolean True or False value. Let’s use these operators to compare strings.

Compare strings to check if they are equal using == operator using Python

Suppose we have two strings i.e.

firstStr = "sample"
secStr   = "sample"

Now let’s use == operator to match the contents of both the strings i.e.

if firstStr == secStr:
    print('Both Strings are same')
else:
    print('Strings are not same')

Output:

Both Strings are same

As contents of both the strings were exactly same, so == operator returned True. But this is a case sensitive match. Now let’s see how to compare strings in case insensitive manner,

Compare strings by ignoring case using Python

Suppose we have two strings i.e.

firstStr = "SAMple"
secStr = "sample"

As both the strings has similar characters but in different case. So to match these strings by ignoring case we need to convert both strings to lower case and then match using operator == i.e.

if firstStr.lower() == secStr.lower():
    print('Both Strings are same')
else:
    print('Strings are not same')

Output:

Both Strings are same

It matched the strings in case in sensitive manner.

Check if strings are not equal using != operator using Python

To confirm if the contents of two strings are not same we can use != operator too. Let’s see an example,

Suppose we have two strings i.e.

firstStr = "this is"
secStr   = "not this"

Now let’s check if both strings contains different text i.e.

if firstStr != secStr:
    print('Both Strings are not equal')
else:
    print('Strings are equal')

Output:

Both Strings are not equal

As contents of both the strings were different, so operator != returned True.

Check if one string is greater than or less than other string.

Operator <, > , <=, >= compares the strings in alphabetical order. For example

  • “abcd” is greater than “abcc”
  • “abc” is less than “Abc”
  • “abcdd” is greater than “abc”

Let’s see actual example,

if "abcd" > "abcc":
    print('"abcd" is greater than "abcc"')

if "Abc" < "abc":
    print('"Abc" is less than "abc"')

if "abcdd" > "abc":
    print('"abcdd" is greater than "abc"')

Output:

"abcd" is greater than "abcc"
"Abc" is less than "abc"
"abcdd" is greater than "abc"

Similarly we can use <= & >= operator to compare strings in lexical order.

Comparing strings : is vs == Operator

Sometimes is operator is also used to compare strings to check if they are equal or not. But it will not always work because there is a fundamental difference in functionality of is and == operator in python.

is operator

It’s used to checks for the equality of two objects i.e. if two given variables points to same object or not. Let’s understand by examples,
Suppose we have two string objects i.e.

firstStr = "sample"
secStr   = "sample"

Now both the variables firstStr & secStr points to same object. We can confirm by print their object ID’s i.e.

if firstStr is secStr:
    print('Both the objects are equal i.e. points to same object')

print("Object ID of First object :" , id(firstStr))
print("Object ID of Second object :", id(secStr))

Output:

Both the objects are equal i.e. points to same object
Object ID of First object : 53526272
Object ID of Second object : 53526272

Now we will compare these two string variable using is operator, then it will check if both the variables points to same object internally i.e.

if firstStr is secStr:
    print('Both the objects are equal')

Output:

Both the objects are equal.

As both variables were referring to same object, so is operator returned True.

Now let’s change the second variable secStr i.e.

secStr = "sample is".split()[0]

Now print the contents and object ID of both the objects i.e.

print('firstStr: ', firstStr, " : Object ID :", id(firstStr))
print('secStr: ', secStr, " : Object ID :", id(secStr))

Output:

firstStr:  sample  : Object ID : 50380544
secStr:  sample  : Object ID : 7466304

Contents of both the object is same but both are referring to different object. Now let’s compare these using is operator i.e.

if firstStr is secStr:
    print('Both the objects are equal i.e. points to same object')
else:
    print('Both the objects are different')

Output:

Both the objects are different

Although, both the strings had same contents but they were referring to different objects internally, so is operator returned False.

Compare contents using == operator

So, to compare and check if the contents of a two strings are equal, we should use == operator i.e. for above string objects == operator will return True i.e.

if firstStr == secStr:
    print('Contents of both Strings are same')

Output:

Contents of both Strings are same

Compare strings using Regex in Python

Python provides a module re for regular expression matching operations. We can use that to compare strings using regex patterns.

Suppose we have few IPs like,

[ "192.122.78.11", "192.122.78.305" , "192.122.77.111"]

and we want to check if all these IP matches the sub-net mask of “192.122.78.XXX” using regex module of python.

For that first of all import the re module i.e.

import re

Now let’s create a regex pattern to match the IP strings with subnet mask i.e.

# Create regex pattern
regexPattern = re.compile("192.122.78.*")

It returns a Pattern object. We can use the Pattern.fullmatch(string[, pos[, endpos]]) to check if whole string matches this regular expression i.e.

listOfIps = [ "192.122.78.11", "192.122.78.305" , "192.122.77.111"]

# Check if strings in list matches the regex pattern
for ipStr in listOfIps:
    matchObj = regexPattern.fullmatch(ipStr)
    if matchObj:
        print('Contents of string ' ,ipStr , ' matched the pattern')
    else:
        print('Contents of string ' ,ipStr , ' do not matched the pattern')

Output:

Contents of string  192.122.78.11  matched the pattern
Contents of string  192.122.78.305  matched the pattern
Contents of string  192.122.77.111  do not matched the pattern

It shows which IP strings completely matches our regex pattern.

Complete example is as follows,

import re

def main():

    print('Compare to check if two strings are equal')

    firstStr = "sample"
    secStr   = "sample"

    if firstStr == secStr:
        print('Both Strings are same')
    else:
        print('Strings are not same')

    print('Compare two strings by ignoring case')

    firstStr = "SAMple"
    secStr = "sample"

    if firstStr.lower() == secStr.lower():
        print('Both Strings are same')
    else:
        print('Strings are not same')

    print('Compare to check if two strings are not equal using != operator')

    firstStr = "this is"
    secStr   = "not this"

    if firstStr != secStr:
        print('Both Strings are not equal')
    else:
        print('Strings are equal')

    print('Check if one string is greater or less than other string')

    if "abcd" > "abcc":
        print('"abcd" is greater than "abcc"')

    if "Abc" < "abc":
        print('"Abc" is less than "abc"')

    if "abcdd" > "abc":
        print('"abcdd" is greater than "abc"')

    print('Comparing strings : is vs == operator')

    firstStr = "sample"
    secStr   = "sample"

    if firstStr is secStr:
        print('Both the objects are equal i.e. points to same object')

    print("Object ID of First object :" , id(firstStr))
    print("Object ID of Second object :", id(secStr))


    secStr = "sample is".split()[0]

    print('firstStr: ', firstStr, " : Object ID :", id(firstStr))
    print('secStr: ', secStr, " : Object ID :", id(secStr))

    if firstStr is secStr:
        print('Both the objects are equal i.e. points to same object')
    else:
        print('Both the objects are different')

    if firstStr == secStr:
        print('Contents of both Strings are same')

    print('Comparing strings Using regex')

    # Create regex pattern
    regexPattern = re.compile("192.122.78.*")

    listOfIps = [ "192.122.78.11", "192.122.78.305" , "192.122.77.111"]

    # Check if strings in list matches the regex pattern
    for ipStr in listOfIps:
        matchObj = regexPattern.fullmatch(ipStr)
        if matchObj:
            print('Contents of string ' ,ipStr , ' matched the pattern')
        else:
            print('Contents of string ' ,ipStr , ' do not matched the pattern')




if __name__ == '__main__':
   main()

Output:

Compare to check if two strings are equal
Both Strings are same
Compare two strings by ignoring case
Both Strings are same
Compare to check if two strings are not equal using != operator
Both Strings are not equal
Check if one string is greater or less than other string
"abcd" is greater than "abcc"
"Abc" is less than "abc"
"abcdd" is greater than "abc"
Comparing strings : is vs == operator
Both the objects are equal i.e. points to same object
Object ID of First object : 50904832
Object ID of Second object : 50904832
firstStr:  sample  : Object ID : 50904832
secStr:  sample  : Object ID : 10743104
Both the objects are different
Contents of both Strings are same
Comparing strings Using regex
Contents of string  192.122.78.11  matched the pattern
Contents of string  192.122.78.305  matched the pattern
Contents of string  192.122.77.111  do not matched the pattern

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top