Python String compare

Previous
Next

In this post, we will see how to compare two Strings in Python.

You don’t any specific methods to compare Strings in python. You can use different operators such == and =! for String comparison. You can also use <, >, <=, >= with Strings.

Let’s understand with the help of example:

str1 = "hello" str2 = "hello" str3 = "HELLO" str4= "hi" print(str1==str2) print(str1==str3) print(str1 > str3) print(str1!=str4)

Output:

True
False
True
True

Let’s understand output now.
str1==str2 returns True:
As str1 and str2 are exactly same String, it return true.

str1==str3 returns False:
As str1 and str2 differ in case, it return false.

str1 > str3 returns True:
> operator checks for unicode and it returns true in this case.

str1!=str4 return True
As str1 and str4 are not equal, it return true.

Case insensitive String compare

In case you want to compare String by case insensitive, you need to use either upper() or lower() with Strings.

str1 = "hello" str2 = "HELLO" print(str1.lower()==str2.lower()) print(str1.upper()==str2.upper())

Output:

True
True

In Python, String is stored as sequence of character and you can use id() function to identify the object.

str1 = "hello" str2 = "hello" str3 = "HELLO" print(id(str1)) print(id(str2)) print(id(str3))

Output:

4512336784
4512336784
4512336952

As you can see id function returned same value for same String.

That’s all about how to compare String in Python.

Previous
Next

Add Comment