Skip to main content
Comparing-Strings-in-Python

Comparing Strings in Python

in this post, We’re going to learn different ways to compare two strings in python. There are no special methods to compare two strings.

The python is providing ‘==’ and ‘!=’ boolean operators to compare strings. You can also use ‘is’ and ‘is not’ operators to compare objects in Python as well as string. There is one more option are ‘<‘ and ‘>’ operators to compare strings.

How to Python String Compare Work

The characters from both strings are used to compare strings in Python. Both strings’ characters are compared one by one. The Unicode value of distinct characters is compared when they are found. A smaller character is one with a lower Unicode value.

Compare String in Python

Let’s take a basic example for each method and compare strings.

Comparing Python strings using the == and != operators

We can use the boolean operators “==” and “! =” to compare two strings. The “==” operator is used to check strings are equal and “!=” operator to check strings is not equal. Depending on the result, these operations will produce a boolean value of True or False.

username = 'adam'
password = 'adam'
print(password == username)

Output:

True

Check not equal to the string:

username = 'adam'
password = 'Test'
print(password != username)

Output:

True

String comparison is case sensitive

The string comparison in python is case sensitive, which means that the strings “test” and “Test” are not equal. Lowercase and uppercase characters have different ASCII codes, as we all know.

username = 'adam'
password = 'Adam'
print(password == username)

Output:

False

Python Compare two string using <, >, <=, >= operator

Let’s compare two strings in python using a greater than comparison operator. The see below python code :

name1 = 'adam'
name2 = 'adam'

if name1 > name2:
 print('Equal')
else:
 print('Not Equal')

Output:

Not Equal

Leave a Reply

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