Comparing Strings In Python – POFTUT

Comparing Strings In Python

A string is a very useful and popular variable type used in the Python programming language. Sometimes we need to operate two or more strings and compare them. Comparing numbers is easy but the string is a bit different and harder. In this tutorial, we will look at different comparison operations on Python strings.

Find Bigger String

Two numbers can be compared in order to find the bigger one but how can we find bigger string. Strings are consist of multiple characters and evaluated according to these multiple characters. Comparing two string means comparing the ASCII values of each character one by one. For example:

Find Bigger String

Find Bigger String

These two strings are very similar but the third character is different for both. If we compare these two strings b will be bigger than a the variable because of d ASCII value is bigger than c ASCII value. And as a result, a boolean value True is returned

Check If Same with == Operator

The most popular comparison operation is checking the two strings if they are the same. We will use == operator in order to check equality.

Check If Same

Check If Same

Check If Same with is Operator

Python programming language also provides is operator to check given objects are the same. We can use is operator in order to check if given two string is the same which means two string provides the same characters in the same order.

LEARN MORE  Linux Bash Arrays and Elements

Check If Same with is Operator

Check If Same with is Operator

Check If Different with != Operator

The reverse of checking equality is checking if two strings are different. If the strings are different from each other this will return boolean True . We will use != operator for these operations.

Check If Different

Check If Different

Check If String Empty

Strings can provide different characters but also can contain no value or just spaces. We can check if a string is empty or not by using strip function. We will strip spaces from the string and check equality with an empty string literal like below.

Check If String Empty

Check If String Empty

We can also use the string with the if keyword. If the string has a value different than space or empty the if will get a True boolean value.

Check If String Empty

Check If String Empty

Compare String Case Insensitive

In some cases, we may have strings those need to be compared in a case insensitive manner. We can use some function provided by the Python string type like lower() and upper(). In this example, we will lower all provided strings and compare them with == and != operators.

LEARN MORE  C - Printf Tutorial with Examples

Compare String Case Insensitive

Compare String Case Insensitive

Leave a Reply

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

Enjoy this blog? Please spread the word :)