HOWTO · Python

How to Compare Two Strings Character by Character in Python

This article explores several methods to compare two strings character by character in Python, each with its advantages and use cases.

On this page

Sometimes a simple equality check is not enough: you need to know how many positions of two strings hold the same character, or exactly where they start to differ. Python has no single built-in that returns a positional match count, but zip() and a generator expression make it a one-liner.

This article shows the zip() approach first, then an index loop for when the positions themselves matter, how to treat strings of different lengths and non-string inputs, how a match count relates to == and Hamming distance, and what the comparison costs.

Compare two strings character by character with zip()

The shortest way to compare two strings position by position is to pair the characters with zip() and count the equal pairs. zip(first, second) yields tuples (first[0], second[0]), (first[1], second[1]), and so on, stopping as soon as the shorter string is used up, so the result is always a count over the shared prefix.

Feeding those pairs through a generator expression into sum() counts each True comparison as one. Run this example:

def count_matching_positions(first, second):
    return sum(a == b for a, b in zip(first, second))


print(count_matching_positions("apple", "apricot"))
print(count_matching_positions("homophones", "homonyms"))
print(count_matching_positions("apple", "applepie"))
2
4
5

"apple" and "apricot" agree in the first two positions only, "homophones" and "homonyms" agree in four of the eight positions zip() produces, and "apple" matches all five characters of the prefix it shares with "applepie". That last result matters: five matching positions does not mean the strings are equal, only that everything zip() compared matched.

One caveat about what a “character” means here: Python iterates a string by Unicode code point, not by what a reader sees as one letter. An "é" written as e followed by a combining accent is two code points, so two visually identical strings can produce different counts until they are normalized with unicodedata.normalize().

Use an index loop when you need positions

zip() tells you whether characters match but discards the index. When you need to know which position differs — to report the first divergence or to restrict the comparison to a slice — drive the loop with range() over the shorter length:

def compare_with_positions(first, second):
    size = min(len(first), len(second))
    matches = 0
    for i in range(size):
        if first[i] == second[i]:
            matches += 1
        else:
            print(f"position {i}: {first[i]!r} versus {second[i]!r}")
    return matches


print("matches:", compare_with_positions("homophones", "homonyms"))
position 4: 'p' versus 'n'
position 5: 'h' versus 'y'
position 6: 'o' versus 'm'
position 7: 'n' versus 's'
matches: 4

A while loop does the same job when you want explicit control over the index: initialize i = 0, loop while i < size, and increment i yourself. enumerate(zip(first, second)) is a third option that hands you (index, (char1, char2)) tuples without a manual counter.

Handle different lengths and non-string inputs

The zip() examples share one contract: both arguments are expected to be strings, and the comparison covers only the shared prefix. Two consequences are worth handling deliberately.

First, zip() never inspects the tail of the longer string. If a trailing remainder should count against the result — as it does for equality — check the lengths yourself, or pair the strings with itertools.zip_longest(first, second, fillvalue=...), which pads the shorter input so every position is visited.

Second, passing None or another non-string is a programming error, not a comparison that happens to find no matches. Returning 0 for count_matching_positions("apple", None) confuses a bad call with a real result. Reject the input instead so the caller finds out:

def count_matching_positions(first, second):
    if not isinstance(first, str) or not isinstance(second, str):
        raise TypeError("expected two strings")
    return sum(a == b for a, b in zip(first, second))


try:
    count_matching_positions("apple", None)
except TypeError as exc:
    print("TypeError:", exc)

print(count_matching_positions("apple", "applepie"))
TypeError: expected two strings
5

Whether len(first) != len(second) should also be rejected depends on the task: a shared-prefix count is legitimate on its own, while an equality-style check should treat different lengths as different strings.

Count matches, test equality, or calculate Hamming distance

A positional match count answers a different question than a string comparison, and picking the wrong one causes subtle bugs:

  • first == second tests whole-string equality: every position matches and the lengths are the same. "apple" == "applepie" is False even though their shared prefix matches completely.
  • all(a == b for a, b in zip(first, second)) looks similar but only proves the shared prefix is equal — it returns True for "apple" and "applepie". Add len(first) == len(second) to make it a real equality test, or simply use ==.
  • Hamming distance goes in the other direction: it counts positions that differ, and it is only defined for strings of equal length. For equal-length inputs it is exactly len(first) minus the match count.
def hamming_distance(first, second):
    if len(first) != len(second):
        raise ValueError("Hamming distance needs strings of equal length")
    return sum(a != b for a, b in zip(first, second))


first, second = "apple", "applepie"
print(first == second)
print(sum(a == b for a, b in zip(first, second)))
print(hamming_distance("karolin", "kathrin"))
False
5
3

"karolin" and "kathrin" differ at positions 2, 3, and 4, so their Hamming distance is 3 — and because the strings have the same length, it equals 7 - 4.

Understand the time and space complexity

Both the zip() count and the index loop inspect at most min(len(first), len(second)) character pairs, so the running time is O(min(len(first), len(second))) — linear in the shorter input. The worst case is reached when the strings match over their whole shared prefix; a loop that stops at the first mismatch can finish sooner.

Auxiliary space is O(1): zip() and the generator expression are lazy iterators that hold only one pair at a time, and the counter is a single integer. Materializing the pairs with list(zip(first, second)) would instead cost O(min(len(first), len(second))) space for no benefit, so keep the generator form.

For context, first == second is also linear in the worst case, though the comparison can stop as soon as a difference is found.