Compare two strings Python | Example code

Use comparison operators to compare two strings in Python. Comparison of strings means wants to know whether both strings are equivalent to each other or not.

Another thing can do in Comparison to find greater or smaller than the other string.

Here some operators will use:-

OperatorsRelational Meaning
==Checks two strings are equal
!=Checks if two strings are not equal
<Checks if the string on its left is smaller compare to other
<=Checks if the string on its left is smaller than or equal to Another
>Check The left side String is greater than that on its right string
>=Checks if the string on its left is greater than or equal to that on its right

How to compare two strings in python example code

Simple python example code.

a = 'A'
b = 'A'
c = 'B'
d = 'BB'

print("Are string equal?")
print(a == b)

print("Are string different?")
print(a != c)

print("Is a less than or equal to d?")
print(a <= d)

print("Is c greater than or equal to d?")
print(c >= d)

print("Is d less than b?")
print(d < b)

Output:

Compare two strings Python

Another simplified example code

print("ABC" == "ABC")
print("ABC" < "abc")
print("ABC" > "abc")
print("ABC" != "ABC")

Output:

True
True
False
False

Q: Why does comparing strings using either ‘==’ or ‘is’ sometimes produce a different result?

Answer: is is identity testing, == is equality testing. what happens in code would be emulated in the interpreter like this:

a = 'pub'
b = ''.join(['p', 'u', 'b'])
print(a == b)
print(a is b)

Output:

True
False

In other words: a is b is the equivalent of id(a) == id(b)

Source: stackoverflow.com

Do comment if you have any doubts and suggestions on this Python string example code.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

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