Languages
[Edit]
EN

Python - compare strings

0 points
Created by:
DoLLot
614

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - compare strings

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join