How to compare strings in Python

Let’s say you want to compare two string to see if they have the same value. You can do it using the comparison operator is equal to which is represented by == (two equal signs).

>>> s1 = 'Dan'
>>> s2 = 'Dumitrache'
>>> if s1 == s2:
...     print('Strings are equal!')
... else:
...     print('Strings are not equal!')
... 
Strings are not equal!

Of course, you could put the whole if-else statement into a function then just call the function.

>>> s1 = 'Dan'
>>> s2 = 'Dumitrache'
def compare_strings():
...     if s1 == s2:
...             print('Strings are equal!')
...     else:
...             print('Strings are not equal!')
... 
>>> compare_strings()
Strings are not equal!

Let’s choose two strings that are equal and then use is to compare if the two variables refer to the same object.

>>> s1 = 'Honda'
>>> s2 = 'Honda'
>>> if s1 == s2:
...     print('Honda is good!')
... else:
...     print('Yamaha is cheaper!')
... 
Honda is good!
>>> 
>>> dir(s1) is dir(s2)
False

As you can see, the two strings are equal but they refer to two different objects.

Let’s try to use other comparison operators on two newly created strings.

>>> s1 = 'dan'
>>> s2 = 'Dan'
>>> s1 > s2
True
>>> s1 != s2
True

Note:
Uppercase letters in Python come first, then lowercase letters. That’s why s1 > s2 returns True.
Other comparison operators can be used.

Leave a Reply