How to Compare Strings in Python
To compare strings in Python, you can use the == operator, the != operator, or the str.casefold() function along with the == operator.
The following examples show how to compare strings in Python.
Using == Operator
We can use the == operator to compare strings.
Suppose we have the following strings:
# Declare strings
string1 = "hello"
string2 = "hello"
# Compare strings
print(string1 == string2)
Output: 👇️
True
In this example, we use the == operator to compare string1 and string2. The output shows True, which means both strings are equal.
Using != Operator
We can use the != operator to compare strings.
Suppose we have the following strings:
# Declare strings
string1 = "hello"
string2 = "hello"
# Compare strings
print(string1 != string2)
Output: 👇️
False
In this example, we use the != operator to compare string1 and string2. The output shows False, which means both strings are equal.
Using str.casefold() Function & == Operator
We can use the str.casefold() function and the == operator to compare strings in a case-insensitive manner.
Suppose we have the following strings:
# Declare strings
string1 = "hello"
string2 = "HELLO"
# Compare strings
print(string1.casefold() == string2.casefold())
Output: 👇️
True
In this example, we use the str.casefold() function to convert both string1 and string2 to lowercase and then use the == operator to compare them. The output shows True, which means both strings are equal.
Conclusion
We can use the == operator, the != operator, and the str.casefold() function along with the == operator to compare strings in Python. These methods provide a convenient way to determine if strings are equal or not.