How to Check If Two Strings are Equal in Python
To check if two strings are equal in Python, you can use the == operator or the eq() method.
The following examples show how to check if two strings are equal in Python.
Using == Operator
We can use the == operator to check if two strings are equal.
Suppose we have the following strings:
# Declare strings
name1 = "Anita"
name2 = "Anita"
# Check whether strings are equal or not
if name1 == name2:
print("The strings are equal.")
else:
print("The strings are not equal.")
Output: 👇️
The strings are equal.
In this example, we use the == operator to check if the strings name1 and name2 are equal.
Using eq() Method
We can use the eq() method to check if two strings are equal.
Suppose we have the following strings:
# Declare strings
name1 = "Anita"
name2 = "Anita"
# Check whether strings are equal or not
if name1.__eq__(name2):
print("The strings are equal.")
else:
print("The strings are not equal.")
Output: 👇️
The strings are equal.
In this example, we use the eq() method to check if the strings name1 and name2 are equal.
Conclusion
We can use the == operator and the eq() method to check if two strings are equal in Python.