Python | Count the Number of matching characters in a pair of string (original) (raw)

Last Updated : 11 Dec, 2025

Given two strings, the task is to count the number of characters that appear in both strings, ignoring case and duplicates if needed.

**Example:

**Input:
s1 = "apple"
s2 = "grape"

**Output: 3

Below are the several methods to perform this task:

Using Set Intersection

This method converts both strings into sets and finds common characters using the intersection.

Python `

s1 = "apple" s2 = "grape"

res = len(set(s1.lower()) & set(s2.lower())) print(res)

`

**Explanation:

Using List Comprehension

This method iterates through one string and checks if each unique character exists in the other string.

Python `

s1 = "apple" s2 = "grape" res = len([c for c in set(s1.lower()) if c in set(s2.lower())]) print(res)

`

**Explanation:

Using a For Loop

This method manually iterates through each character of one string and counts matches in the other string.

Python `

s1 = "apple" s2 = "grape"

a = s1.lower() b = s2.lower() res = 0

for c in set(a): if c in b: res += 1

print(res)

`

**Explanation: