Table of contents
1.
Introduction
2.
Equal to String Python using Relational Operators
2.1.
Python
3.
Equal to String Python using Regular Expression:
3.1.
Python
3.2.
Python
4.
String Comparison in Python using Is Operator
4.1.
Python
4.2.
Python
5.
String Comparison in Python Creating a User-Defined Function
5.1.
Python
5.2.
Python
6.
Frequently Asked Questions
6.1.
Can we compare strings using the greater than (>) or less than (<) operators in Python?
6.2.
Is it possible to compare strings while ignoring case sensitivity?
6.3.
How can we check if a string contains a specific substring?
7.
Conclusion
Last Updated: Aug 8, 2025
Easy

String Comparison in Python

Author Riya Singh
0 upvote

Introduction

In Python, comparing strings is a common task that allows us to determine whether two strings are equal or not. String comparison is essential in various scenarios, like checking user input, validating data, or making decisions based on string values. 

String Comparison in Python

In this article, we will discuss different methods to compare strings in Python, like using relational operators, regular expressions, the "is" operator, & creating user-defined functions. 

Equal to String Python using Relational Operators

Python provides relational operators that allow us to compare strings & determine their equality. The most commonly used relational operator for string comparison is the double equals (==) operator. 

For example : 

  • Python

Python

string1 = "Hello"

string2 = "Hello"

string3 = "World"

if string1 == string2:

   print("string1 & string2 are equal")

else:

   print("string1 & string2 are not equal")

if string1 == string3:

   print("string1 & string3 are equal")

else:

   print("string1 & string3 are not equal")
You can also try this code with Online Python Compiler
Run Code


In this code, we define three string variables: `string1`, `string2`, & `string3`. We use the double equals (==) operator to compare `string1` with `string2` & `string1` with `string3`. The comparison returns a boolean value, either `True` or `False`, depending on whether the strings are equal or not.

The output of this code will be:

string1 & string2 are equal
string1 & string3 are not equal


The double equals operator compares the characters of the strings one by one, taking into account their case-sensitivity. If all the characters match, the strings are considered equal.

It's important to note that the double equals operator is case-sensitive. For example, "Hello" & "hello" are not considered equal. If you want to perform a case-insensitive comparison, you can convert both strings to lowercase or uppercase before comparing them, like this:

string1 = "Hello"
string2 = "hello"
if string1.lower() == string2.lower():
    print("string1 & string2 are equal (case-insensitive)")
else:
    print("string1 & string2 are not equal (case-insensitive)")


In this case, the `lower()` method is used to convert both strings to lowercase before comparing them, resulting in a case-insensitive comparison.

Equal to String Python using Regular Expression:

Regular expressions, also known as regex, provide a powerful way to compare strings based on patterns. Python's `re` module allows us to work with regular expressions & perform string comparisons.

Let's look at an example where we want to check if a string matches a specific pattern:

  • Python

Python

import re

string1 = "Hello, World!"

pattern = r"Hello, .*!"

if re.match(pattern, string1):

   print("string1 matches the pattern")

else:

   print("string1 does not match the pattern")
You can also try this code with Online Python Compiler
Run Code


In this code, we import the `re` module & define a string variable `string1`. We also define a regular expression pattern using the `r` prefix, which indicates a raw string. The pattern `r"Hello, .*!"` matches any string that starts with "Hello, " followed by any number of characters (represented by `.*`) & ends with an exclamation mark.

We use the `re.match()` function to check if `string1` matches the specified pattern. The `match()` function returns a match object if the string matches the pattern, or `None` if there is no match.

The output of this code will be:

string1 matches the pattern


Regular expressions provide a flexible & powerful way to compare strings based on patterns. You can define complex patterns using special characters & metacharacters to match specific substrings or patterns within a string.

Let’s discuss another example that shows the use of regular expressions for string comparison:

  • Python

Python

import re

strings = ["apple", "banana", "cherry", "date"]

pattern = r"^b\w+"

for string in strings:

   if re.match(pattern, string):

       print(f"{string} matches the pattern")

   else:

       print(f"{string} does not match the pattern")
You can also try this code with Online Python Compiler
Run Code


In this code, we have a list of strings called `strings`. We define a regular expression pattern `r"^b\w+"`, which matches any string that starts with the letter "b" followed by one or more word characters (letters, digits, or underscores).

We iterate over each string in the `strings` list & use `re.match()` to check if the string matches the pattern. 

The output will be

apple does not match the pattern
banana matches the pattern
cherry does not match the pattern
date does not match the pattern


Note: Regular expressions offer a wide range of possibilities for string comparison & pattern matching. They allow you to search for specific substrings, validate input, extract information from strings, & more. 

String Comparison in Python using Is Operator

In Python, the `is` operator is used to compare the identity of two objects. It checks whether two variables refer to the same object in memory. When comparing strings using the `is` operator, it compares the memory addresses of the strings rather than their contents.

For example : 

  • Python

Python

string1 = "Hello"

string2 = "Hello"

string3 = "hello"

if string1 is string2:

   print("string1 & string2 refer to the same object")

else:

   print("string1 & string2 refer to different objects")

if string1 is string3:

   print("string1 & string3 refer to the same object")

else:

   print("string1 & string3 refer to different objects")
You can also try this code with Online Python Compiler
Run Code


In this code, we define three string variables: `string1`, `string2`, & `string3`. We use the `is` operator to compare `string1` with `string2` & `string1` with `string3`.

The output of this code will be:

string1 & string2 refer to the same object
string1 & string3 refer to different objects


The reason `string1` & `string2` refer to the same object is due to a optimization technique called string interning. Python caches small strings & reuses them to save memory. When you assign the same string value to multiple variables, they may refer to the same object in memory.

However, it's important to note that string interning is an implementation detail & should not be relied upon for string comparison. The behavior of string interning may vary depending on the Python implementation, version, & the specific strings being compared.

In general, it is recommended to use the double equals (==) operator for string comparison based on their contents, rather than the `is` operator, which compares object identity.

Let’s see an example that shows the difference between the `is` operator & the double equals operator:

  • Python

Python

string1 = "Hello"

string2 = "He" + "llo"

if string1 == string2:

   print("string1 & string2 have the same contents")

else:

   print("string1 & string2 have different contents")

if string1 is string2:

   print("string1 & string2 refer to the same object")

else:

   print("string1 & string2 refer to different objects")
You can also try this code with Online Python Compiler
Run Code


In this code, `string1` & `string2` have the same contents, but they are created differently. `string1` is assigned the literal value "Hello", while `string2` is created by concatenating two strings "He" & "llo".

The output of this code will be

string1 & string2 have the same contents
string1 & string2 refer to different objects


Note: You can see clearly that, the double equals operator (==) correctly identifies that `string1` & `string2` have the same contents, while the `is` operator indicates that they refer to different objects in memory.

String Comparison in Python Creating a User-Defined Function

In addition to using built-in operators & methods for string comparison, you can also create your user-defined functions to compare strings based on specific criteria. This allows you to customize the comparison logic according to your needs.

Let's create a user-defined function that compares two strings & returns `True` if they are equal, ignoring case sensitivity & whitespace:

  • Python

Python

def compare_strings(str1, str2):

   str1 = str1.lower().strip()

   str2 = str2.lower().strip()

   return str1 == str2

string1 = "Hello, World!"

string2 = "  hello, world!  "

string3 = "Hello, Python!"

print(compare_strings(string1, string2)) 

print(compare_strings(string1, string3))
You can also try this code with Online Python Compiler
Run Code


In this code, we define a function called `compare_strings` that takes two string parameters, `str1` & `str2`. Inside the function, we convert both strings to lowercase using the `lower()` method & remove any leading or trailing whitespace using the `strip()` method. Then, we compare the modified strings using the double equals operator (==) & return the result.

We create three string variables: `string1`, `string2`, & `string3`. We call the `compare_strings` function with different combinations of these strings & print the results.

The output will be:

True
False


The `compare_strings` function ignores case sensitivity & whitespace, so `string1` & `string2` are considered equal, while `string1` & `string3` are not.

Creating user-defined functions for string comparison allows you to encapsulate the comparison logic & reuse it throughout your code. You can define the comparison criteria based on your specific requirements, such as ignoring case sensitivity, removing punctuation, or checking for specific patterns.

Here’s an example that shows a user-defined function for string comparison based on a specific pattern:

  • Python

Python

import re

def compare_pattern(str1, pattern):

   return bool(re.match(pattern, str1))

strings = ["apple", "banana", "cherry", "date"]

pattern = r"^b\w+"

for string in strings:

   if compare_pattern(string, pattern):

       print(f"{string} matches the pattern")

   else:

       print(f"{string} does not match the pattern")
You can also try this code with Online Python Compiler
Run Code


In this code, we define a function called `compare_pattern` that takes a string `str1` & a regular expression pattern. The function uses the `re.match()` function to check if the string matches the pattern & returns a boolean value using the `bool()` function.

We have a list of strings & a regular expression pattern `r"^b\w+"`, which matches any string that starts with the letter "b" followed by one or more word characters.

We iterate over each string in the `strings` list, call the `compare_pattern` function with the string & the pattern, & print the results.

The output will be:

apple does not match the pattern
banana matches the pattern
cherry does not match the pattern
date does not match the pattern

Frequently Asked Questions

Can we compare strings using the greater than (>) or less than (<) operators in Python?

Yes, you can use the > & < operators to compare strings lexicographically, based on their ASCII values.

Is it possible to compare strings while ignoring case sensitivity?

Yes, you can convert the strings to lowercase or uppercase using the lower() or upper() methods before comparing them.

How can we check if a string contains a specific substring?

You can use the in operator or the find() method to check if a substring exists within a string.

Conclusion

In this article, we learned about various methods for comparing strings in Python. We explained this using relational operators like == for equality comparison, regular expressions for pattern matching, the is operator for object identity comparison, & creating user-defined functions for custom comparison logic. String comparison is a fundamental task in Python programming & learning these techniques will help you evaluate strings effectively.

Live masterclass