compare strings in python

How to Compare Strings in Python

Python makes it easy to work with strings using intuitive operators and functions. Often you may need to compare strings, literal or variable, with each other in your python application or website. In this article, we will learn how to compare strings in Python.


How to Compare Strings in Python

You can compare strings using == & != operator, or using is & not is operator. We will look at each of these cases one by one.



1. Using == and != operators

== and != are commonly used string operators in python to check if two strings are equal or unequal respectively. They both check the Unicode values of string elements and return True/False. By default, python stores each string character as Unicode, making it easy to compare strings no matter which encoding it is present in. Here are the examples to check if the two strings are equal using == operator.

a='hello'
b='world'
c='hello'
a==b
False
a==c
True

Similarly, we use != operator to check if the strings are unequal.

>>> a='hello'
>>> b='world'
>>> c='hello'
>>> a!=b
True
>>> a!=c
False

Similarly, you can also use these operators to compare two literals or a string variable with a literal, as shown below.

>>> a='hello'
>>> a=='hello'
True
>>> 'Hello'=='hello'
False


2. Using is and is not operators

Python also provides ‘is’ and ‘is not’ operators to check strings. But unlike == & != operators, is and not is compares the identity of strings, and returns True if they have same id value. Here is an example to demonstrate it.

>>> a='hello'
>>> b='world'
>>> c='hello'
>>> id(a)
55769888L
>>> id(c)
55769888L
>>> id(b)
55769968L
>>> a is b
False
>>> a is c
True

Similarly, you can use is not operator to check if two strings are equal or not.

>>> a='hello'
>>> b='world'
>>> c='hello'
>>> id(a)
55769888L
>>> id(c)
55769888L
>>> id(b)
55769968L
>>> a is not b
True
>>> a is not c
False

Similarly, you can also use these operators to compare two literals or a string variable with a literal, as shown below.

>>> a='hello'
>>> a is 'hello'
True
>>> 'Hello' is 'hello'
False

Remember that python objects can be used to compare only objects of same data type. It is the best practice to use == operator instead of use ‘is’ operator.

Also read:

How to Copy List in Python
How to Copy Files in Python
How to Comment in Python
Git Rename Local & Remote Branch
How to Create Remote Git Branch

Leave a Reply

Your email address will not be published.