Equals. In Python strings can be compared for exact equality with 2 equals signs. With this syntax, the characters (and their cases) are compared.
With casefold, we can fold character cases and use case-insensitive compares. So the letter "B" is equal to "b." This is similar to using lower().
Example. Here we test strings for equality. We have several string literals in the program. We use two equals to check character data.
Tip Newer versions of Python support the casefold method. Similar to lower(), it handles Unicode characters better.
Also We can use the lower method to standardize the casing of strings in our programs.
value = "CAT"
if value == "cat":
print("A") # Not reached.
if value == "CAT":
print("B")
if str.casefold(value) == "cat":
print("C")
if str.lower(value) == "cat":
print("D")B
C
D
Equals, not equals. With the equals operator, the characters of two strings are compared. It does not matter if they are different object instances.
location1 = "forest"
location2 = "FOREST".lower()
# These two strings are equal.
if location1 == location2:
print("In forest")
# These two strings are not equal.
if location1 != "desert":
print("Not in desert")In forest
Not in desert
Some notes, performance. It is fastest to avoid creating temporary strings (as with the lower method) before testing equality. Usually, avoiding allocations helps performance.
We can use the equals and not-equals operators to compare two strings. Often we do this in an if-statement, but the expression can be used in any part of a program.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.