How to Compare Items of Two Strings in Python?

Estimated read time 2 min read

To compare items (characters) of two strings in Python, you can iterate over the characters of each string and compare them one by one. Here’s an example using a loop:

string1 = "hello"
string2 = "world"

# Ensure strings are of equal length
if len(string1) != len(string2):
    print("Strings are not of equal length")
    for i in range(len(string1)):
        if string1[i] > string2[i]:
            print(string1[i], "in string1 is greater than", string2[i], "in string2")
        elif string1[i] < string2[i]:
            print(string1[i], "in string1 is less than", string2[i], "in string2")
            print(string1[i], "in string1 is equal to", string2[i], "in string2")

In this example, we have two strings, string1 and string2. We first check if the strings have equal length. If they are of different lengths, a message is printed indicating that the strings are not comparable. If the lengths are equal, we iterate over the characters of both strings using the range() function and compare each pair of characters.

Within the loop, we use comparison operators (>, <, ==) to compare the characters of string1 and string2. Depending on the result of the comparison, a corresponding message is printed.

You can modify the string1 and string2 variables in the example above to compare any other pair of strings.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply