Python if string equals | Example code

Use the equality (‘==’) operator to check if strings are equal or not. It will work case-sensitive manner i.e. uppercase letters and lowercase letters would be treated differently.

string1 == string2

Python ‘==’ operator compares the string in a character-by-character manner and returns True if the two strings are equal, otherwise, it returns False.

Check if one string equal to another string in Python

Python Example code if string equals.

str1 = "Python"

str2 = "Python"

str3 = "Java"

print(str1 == str2)

print(str1 == str3)

Output:

Python if string equals

Python if string equals Example

Execute the if block if string are equals

str1 = "Python"

str2 = "Python"

if str1 == str2:
    print("Hello world")

Output: Hello world

Another way to us it “!=” operator for String comparison

The ‘!=’ operator compares two strings and returns True if the strings are unequal, otherwise, it returns False.

str1 = "Python"

str2 = "Python"

if str1 != str2:
    print("Hello")
else:
    print("Bye")

Output: Bye

Using ‘is’ operator

the ‘is‘ operator checks whether both the operands refer to the same object or not.

str1 = "Python"

str2 = "Python"

if str1 is str2:
    print("Equal")
else:
    print("Not Equal")

Output: Equal

The __eq__() function to perform string equals check in python

The eq() function basically compares two objects and returns True if found equal, otherwise, it returns False.

str1 = "Python"

str2 = "Python"

if str1.__eq__(str2):
    print("Equal")
else:
    print("Not Equal")

Output: Equal

Do comment if you have any doubts and suggestions on this python string topic.

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.