EN
Python - compare strings
0
points
In this article, we would like to show you how to compare strings in Python.
Quick solution:
string1 = 'text 1'
string2 = 'text 2'
print(string1 is string2) # False
print(string1 == string2) # False
1. Using ==
and is
operators
In this example, we use ==
and is
operators to check if strings have the same value (if they are equal).
string1 = 'text 1'
string2 = 'text 2'
string3 = 'text 1'
print(string1 is string3) # True
print(string2 is string3) # False
print(string1 == string3) # True
print(string2 == string3) # False
Output:
True
False
True
False
2. Using ==
, <
and >
comparators
In this example, we use ==
, <
and >
operators to check which string should be first according to alphabet letters priority.
print('a' == 'a') # True
print('a' < 'b') # True
print('b' > 'a') # True
print('aab' == 'aab') # True
print('aac' > 'aaa') # True
print('123' < '321') # True
print('a' < 'a') # False
print('a' < 'b') # True
print('b' < 'a') # False
print('aab' > 'aab') # False
print('aac' > 'aaa') # True
print('123' > '321') # False
print('aab' == 'aab') # True
print('aac' > 'aaa') # True
print('123' < '321') # True
print('a' < 'a') # False
print('a' < 'b') # True
print('b' < 'a') # False
print('aab' > 'aab') # False
print('aac' > 'aaa') # True
print('123' > '321') # False