EN
Python - compare strings
0 points
In this article, we would like to show you how to compare strings in Python.
Quick solution:
xxxxxxxxxx
1
string1 = 'text 1'
2
string2 = 'text 2'
3
4
print(string1 is string2) # False
5
print(string1 == string2) # False
In this example, we use ==
and is
operators to check if strings have the same value (if they are equal).
xxxxxxxxxx
1
string1 = 'text 1'
2
string2 = 'text 2'
3
4
string3 = 'text 1'
5
6
print(string1 is string3) # True
7
print(string2 is string3) # False
8
9
print(string1 == string3) # True
10
print(string2 == string3) # False
Output:
xxxxxxxxxx
1
True
2
False
3
True
4
False
In this example, we use ==
, <
and >
operators to check which string should be first according to alphabet letters priority.
xxxxxxxxxx
1
print('a' == 'a') # True
2
print('a' < 'b') # True
3
print('b' > 'a') # True
4
5
print('aab' == 'aab') # True
6
print('aac' > 'aaa') # True
7
print('123' < '321') # True
8
9
print('a' < 'a') # False
10
print('a' < 'b') # True
11
print('b' < 'a') # False
12
13
print('aab' > 'aab') # False
14
print('aac' > 'aaa') # True
15
print('123' > '321') # False
16
17
print('aab' == 'aab') # True
18
print('aac' > 'aaa') # True
19
print('123' < '321') # True
20
21
print('a' < 'a') # False
22
print('a' < 'b') # True
23
print('b' < 'a') # False
24
25
print('aab' > 'aab') # False
26
print('aac' > 'aaa') # True
27
print('123' > '321') # False