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

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

We are given two strings. We need to find the count it of the characters in the first string which are also present in a second string.

## With set

The set function gives us unique values all the elements in a string. We also use the the & operator which finds the common elements between the two given strings.

## Example

Live Demo

strA = 'Tutorials Point'
uniq_strA = set(strA)
# Given String
print("Given String\n",strA)
strB = 'aeio'
uniq_strB = set(strB)
# Given String
print("Search character strings\n",strB)
common_chars = uniq_strA & uniq_strB
print("Count of matching characters are : ",len(common_chars))

## Output

Running the above code gives us the following result −

Given String
Tutorials Point
Search character strings
aeio
Count of matching characters are : 3

## With re.search

We use the search function from the re module. We use a count variable and keep incrementing it when the search result is true.

## Example

Live Demo

import re
strA = 'Tutorials Point'
# Given String
print("Given String\n",strA)
strB = 'aeio'
# Given String
print("Search character strings\n",strB)
cnt = 0
for i in strA:
if re.search(i, strB):
cnt = cnt + 1
print("Count of matching characters are : ",cnt)

## Output

Running the above code gives us the following result −

Given String
Tutorials Point
Search character strings
aeio
Count of matching characters are : 5