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:
- **s1.lower(), s2.lower(): Converts both strings to lowercase for case-insensitive comparison.
- **set(...): Removes duplicates and allows fast comparison.
- ****& (intersection):** Finds characters common to both sets.
- **len(): Counts the number of common characters.
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:
- **set(...): Ensures only unique characters are considered.
- List comprehension collects characters present in both strings.
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:
- **a = s1.lower(), b = s2.lower(): Convert strings to lowercase for case-insensitive comparison.
- **set(a): Get unique characters from s1.
- **for c in set(a): if c in b: Check if each unique character exists in s2.
- **res += 1: Count each matching character.