Python provides the equal “==” and not equal “!=” operators in order to compare strings that can be a string value or string variable. The comparison results boolean values True
or False
according to the situations.
Check If String Variables Are Equal
The equality operator ==
can be used to check if the provided string variables are equal. If provided string variables are equal the boolean True
value is returned. If the provided string variables are not equal the boolean False
value is returned.
a = "ismail"
b = "ismail"
c = "ahmet"
if a == b:
print("a and b are equal")
if a == c:
print("a and c are equal")
a and b are equal
As the a and b string variables are equal the “a and b are equal” message is printed to the terminal. But the a and c string variables are not equal and the “a and c are equal message” is not printed to the terminal.
Check If String Values Are Equal
The string values can be also compared with the equal comparison operator.
a = "ismail"
if "ismail" == "ismail":
print("Equal")
if "ismail" == "ahmet":
print("Equal")
if "ismail" == a:
print("a is equal with 'ismail'")
Check If String Variables Are Not Equal
Not equal operator is used to check if provided string variables are not equal. If the provided string variables are not equal the True
boolean value is returned. If the provided string variables are equal the False
boolean value is returned.
a = "ismail"
b = "ismail"
c = "ahmet"
if a != b:
print("a and b are not equal")
if a != c:
print("a and c are not equal")
a and c are not equal
Check If String Values Are Not Equal
String values can be also checked against for their inequality.
a = "ismail"
if "ismail" != "ismail":
print("Equal")
if "ismail" != "ahmet":
print("Equal")
if "ismail" != a:
print("a is equal with 'ismail'")