Python Comparing Strings

We can use the relational operators like >, >=, <, <=, == or != operators to compare two strings. They return Boolean value, i.e. either True or False depending on the strings being compared.

Strings Compare

CopiedCopy Code

s1='Box' 
s2='Boy' 
if(s1==s2): 
print('Both are same') 
else: 
print('Not same')

Strings less than:

While comparing the strings, Python interpreter compares them by taking them in English dictionary order. The string which comes first in the dictionary order will have a low value than the string which comes next.

CopiedCopy Code

if s1<s2: 
print('s1 less than s2') 
else: 
print('s1 greater than or equal to s2')

Strings not equal

CopiedCopy Code

s1='Box' 
s2='Boy' 
if(s1!=s2): 
print('Both are same') 
else: 
print('Not same')

Strings greater than:

CopiedCopy Code

s1='Box' 
s2='Boy' 
if(s1>s2): 
print('Both are same') 
else: 
print('Not same')