5.8 Comparing Strings

Strings can be compared in various ways using relational operators, similar to how numbers are compared.

However, since strings consist of characters, these comparisons are performed character by character, based on each character’s ASCII (or Unicode) value.

M a r y
77 97 114 121

 

M r k
77 97 114 107

 

Strings can be compared using

  • Equality and inequality: ==, !=
  • Relational operator: >, <, >=, <=
  • Case Sensitivity: String comparisons are case-sensitive, meaning 'Hello' and 'hello' are considered not equal.
  • These comparisons are done character by character from left to right, using the ASCII value of each character.

def main():

   str1 = “Mark”
   str2 = “Mary”

   if str1 > str2:
        print(“str1 is greater than str2”)
   elif str1 < str2:            
        print(“str2 is greater than str1”)
   else
        print(“Two strings are equivalent”)

main()


str2 is greater than str1