Python Compare Two Strings Character by Character


In this article, we are going to how to compare two strings character by character in Python using 3 different ways.

    Table of Contents

  1. Compare Two Strings Character by Character Using For Loop
  2. Compare Two Strings Character by Character Using While Loop
  3. Compare Two Strings Character by Character Using Zip
  4. Conclusion

Python Compare Two Strings Character by Character

1. Compare Two Strings Character by Character Using For Loop

The first way to compare two strings character by character is to use a for loop.

First, check if the length of the two strings are equal. If they are not then return False.

If length is equal then proceed further to compare. If all the characters are equal then return True else return False.

# function to compare two strings character by character
def compare_strings(str1, str2):
    if len(str1) != len(str2):
        return False
    else:
        for i in range(len(str1)):
            if str1[i] != str2[i]:
                return False
        return True

str1 = "Hello"
str2 = "Hello"
print(compare_strings(str1, str2))

Output:

True

2. Compare Two Strings Character by Character Using While Loop

The second way to compare two strings character by character is to use a while loop.

Again we follow the same approach as we did above but this time we use a while loop.

Create a variable i and initialize it to 0. This will be used to iterate over the strings.

Check if the length of the two strings are equal. If they are not then return False.

If length is equal then proceed further to compare. If all the characters are equal then return True else return False.

# function to compare two strings character by character
def compare_strings(str1, str2):
    i = 0
    while i < len(str1):
        if str1[i] != str2[i]:
            return False
        i += 1
    return True

str1 = "Hello"
str2 = "Hello"
print(compare_strings(str1, str2))

Output:

True

3. Compare Two Strings Character by Character Using Zip

The third way to compare two strings character by character is to use zip() method.

The zip() method returns a zip object which is an iterator of tuples. Each tuple contains the nth element of each list. The tuple can be unpacked to separate the elements.

For example, if the two strings are "Hello" and "World", then the zip object will be: [('H', 'W'), ('e', 'o'), ('l', 'r'), ('l', 'd')].

Let's use this zip object to compare the two strings character by character.

# compare string using zip method
def compare_strings(str1, str2):
    for (x, y) in zip(str1, str2):
        if x != y:
            return False
    return True

print(compare_strings("Hello", "World")) # False
print(compare_strings("Hello", "Hello")) # True

Conclusion

This is the end of this brief article to compare two strings character by character in Python.

Learn string comparison in python in detail.