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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads