Python - How to compare strings

By xngo on June 7, 2019

#!/usr/bin/python3
# Description: How to compare strings.
 
str_a = 'openwritings.net'
str_b = 'OpenWritings.net'
 
# Compare two strings.
if str_a == str_b:
    print("Case sensitive comparison: {} is equal to {}.".format(str_a, str_b))
else:
    print("Case sensitive comparison: {} is NOT equal to {}.".format(str_a, str_b))
 
# Case insensitive comparison: Ignore lower or upper case.
#   Note: This is not full proof against unicode characters.
if str_a.lower() == str_b.lower():
    print("Case insensitive comparison: {} is equal to {}.".format(str_a, str_b))
else:
    print("Case insensitive comparison: {} is NOT equal to {}.".format(str_a, str_b))

Output

Case sensitive comparison: openwritings.net is NOT equal to OpenWritings.net.
Case insensitive comparison: openwritings.net is equal to OpenWritings.net.

Reference

  • https://stackoverflow.com/questions/319426/how-do-i-do-a-case-insensitive-string-comparison

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.