VOOZH about

URL: https://www.geeksforgeeks.org/python/python-count-the-number-of-matching-characters-in-a-pair-of-string/

⇱ Python | Count the Number of matching characters in a pair of string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python | Count the Number of matching characters in a pair of string

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.


Output
3

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.


Output
3

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.


Output
3

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.

Related Articles:

Comment