Open In App

String Comparison in Python

Last Updated : 25 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

String comparison is a fundamental operation in any programming language, including Python. It enables us to ascertain strings’ relative positions, ordering, and equality. Python has a number of operators and techniques for comparing strings, each with a specific function. We will examine numerous Python string comparison methods in this article and comprehend how to use them.

Input: "Geek" == "Geek"
"Geek" < "geek"
"Geek" > "geek"
"Geek" != "Geek"
Output: True
True
False
False
Explanation: In this, we are comparing two strings if they are equal to each other.

Python String Comparison

Equal to String Python using Relational Operators

The relational operators compare the Unicode values of the characters of the strings from the zeroth index till the end of the string. It then returns a boolean value according to the operator used. It checks Python String Equivalence.

Python3




print("Geek" == "Geek")
print("Geek" < "geek")
print("Geek" > "geek")
print("Geek" != "Geek")


Output

True
True
False
False

Equal to String Python using Regular Expression

In Python, you can use regular expressions to check Python String Equivalence using the re module. Regular expressions provide a flexible and powerful way to define patterns and perform pattern-matching operations on strings.

Python3




import re
 
def compare_strings(string1, string2):
    pattern = re.compile(string2)
    match = re.search(pattern, string1)
 
    if match:
        print(f"'{string2}' found in '{string1}'")
    else:
        print(f"'{string2}' not found in '{string1}'")
 
string1 = "GeeksForGeeks"
string2 = "GeeksFor"
string3 = "Geeks"
 
compare_strings(string1, string2) 
compare_strings(string1, string3)


Output

'GeeksFor' found in 'GeeksForGeeks'
'Geeks' found in 'GeeksForGeeks'

String Comparison in Python using Is Operator

The == operator compares the values of both operands and checks for value equality. Whereas is operator checks whether both the operands refer to the same object or not. The same is the case for != and is not. Let us understand Python String Equivalence with an example.

Python3




str1 = "Geek"
str2 = "Geek"
str3 = str1
 
print("ID of str1 =", hex(id(str1)))
print("ID of str2 =", hex(id(str2)))
print("ID of str3 =", hex(id(str3)))
print(str1 is str1)
print(str1 is str2)
print(str1 is str3)
 
str1 += "s"
str4 = "Geeks"
 
print("\nID of changed str1 =", hex(id(str1)))
print("ID of str4 =", hex(id(str4)))
print(str1 is str4)


Output

ID of str1 = 0x7f6037051570
ID of str2 = 0x7f6037051570
ID of str3 = 0x7f6037051570
True
True
True
ID of changed str1 = 0x7f60356137d8
ID of str4 = 0x7f60356137a0
False

The object ID of the strings may vary on different machines. The object IDs of str1, str2, and str3 were the same therefore the result is True in all the cases. After the object id of str1 is changed, the result of str1 and str2 will be false. Even after creating str4 with the same contents as in the new str1, the answer will be false as their object IDs are different. Vice-versa will happen with is not.

String Comparison in Python Creating a User-Defined Function.

By using relational operators we can only check Python String Equivalence by their Unicode. In order to compare two strings according to some other parameters, we can make user-defined functions. In the following code, our user-defined function will compare the strings based on the number of digits.

Python3




# function to compare string
# based on the number of digits
def compare_strings(str1, str2):
    count1 = 0
    count2 = 0
     
    for i in range(len(str1)):
        if str1[i] >= "0" and str1[i] <= "9":
            count1 += 1
     
    for i in range(len(str2)):
        if str2[i] >= "0" and str2[i] <= "9":
            count2 += 1
     
    return count1 == count2
 
 
print(compare_strings("123", "12345"))
print(compare_strings("12345", "geeks"))
print(compare_strings("12geeks", "geeks12"))


Output

False
False
True


Previous Article
Next Article

Similar Reads

Python | Consecutive String Comparison
Sometimes, while working with data, we can have a problem in which we need to perform comparison between a string and it's next element in a list and return all strings whose next element is similar list. Let's discuss certain ways in which this task can be performed. Method #1 : Using zip() + loop This is one way in which this task can be performe
3 min read
Case-insensitive string comparison in Python
We generally use Python lists to store items. An online shopping application may contain a list of items in it so that the user can search the item from the list of items. For example, Our shopping application has a list of laptops it sells. List contains many brands and one of them is 'Lenovo'. If we want to buy a laptop of Lenovo brand we go to t
4 min read
Python | Data Comparison and Selection in Pandas
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier. The most important thing in Data Analysis is comparing values and selecting data accordingly. The "==" operator works for multiple valu
2 min read
Python | Excel File Comparison
Given Two Excel Files, We want to compare the values of each column row-wise after sorting the values and print the changed column name and row number and values change. Input : Two Excel files Output : Column name : 'location' and Row Number : 0 Column name : 'location' and Row Number : 3 Column name : 'date' and Row Number : 1 Code : Python code
1 min read
Python Object Comparison : "is" vs "=="
Both "is" and "==" are used for object comparison in Python. The operator "==" compares values of two objects, while "is" checks if two objects are same (In other words two references to same object). # Python program to demonstrate working of # &quot;==&quot; # Two different objects having same values x1 = [10, 20, 30] x2 = [10, 20, 30] # Comparis
2 min read
Python | Tkinter ttk.Checkbutton and comparison with simple Checkbutton
Tkinter is a GUI (Graphical User Interface) module which comes along with the Python itself. This module is widely used to create GUI applications. tkinter.ttk is used to create the GUI applications with the effects of modern graphics which cannot be achieved using only tkinter. Checkbutton is used to select multiple options. Checkbuttons can be cr
2 min read
Python | Find Hotel Prices using Hotel price comparison API
Makcorps hotel API is used to get JSON data, to compare Hotel prices, ratings, and reviews from more than 200 websites including; Agoda.com, Hotels.com, Expedia and more. It is organized around GET Requests. One can use this API for free to get information for any hotel or any city regarding prices, ratings, reviews, historical prices and many othe
3 min read
Face Comparison Using Face++ and Python
Prerequisites: Python Programming Language Python is a high-level general-purpose language. It is used for multiple purposes like AI, Web Development, Web Scraping, etc. One such use of Python can be Face Comparison. A module name python-facepp can be used for doing the same. This module is for communicating with Face++ facial recognition service.
3 min read
Comparison of Python with Other Programming Languages
Python is an easily adaptable programming language that offers a lot of features. Its concise syntax and open-source nature promote readability and implementation of programs which makes it the fastest-growing programming language in current times. Python has various other advantages which give it an edge over other popular programming languages su
3 min read
Python - Similar characters Strings comparison
Given two Strings, separated by delim, check if both contain same characters. Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!' Output : True Explanation : Same characters, just diff. positions. Input : test_str1 = 'e!e!k!s', test_str2 = 'g!e!e!k!s', delim = '!' Output : False Explanation : g missing in 1st String. Method #1 : U
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg