how to compare strings in python

Published on Aug. 22, 2023, 12:16 p.m.

The most commonly used method to compare strings in Python is through the use of comparison operators like ==, !=, <, >, <=, and >=. These operators compare strings lexicographically based on their Unicode code points. Here is an example:

str1 = "hello"
str2 = "world"

if str1 == str2:
    print("The strings are equal")
else:
    print("The strings are not equal")

In this example, the == operator is used to compare the two strings. The output of the program will be “The strings are not equal”.

You can also use the is operator to compare the memory location of two strings, but this will only be true if the two variables reference the same string object.

Another useful method of comparing strings is the built-in str.compare() method.This method returns an integer indicating the relationship between two strings. The returned value will be 0 if the two strings are equal, a negative value if the first string is lexicographically less than the second string, and a positive value if the first string is lexicographically greater than the second string.

str1 = "hello"
str2 = "world"

result = str1.compare(str2)

if result == 0:
    print("The strings are equal")
elif result < 0:
    print("The first string is lexicographically less than the second string")
else:
    print("The first string is lexicographically greater than the second string")

In this example, the str.compare() method is used to compare the two strings. The output of the program will be “The first string is lexicographically less than the second string”.

Tags:

related content