
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Count the Number of matching characters in a pair of string in Python
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
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
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
- Related Articles
- Count the Number of matching characters in a pair of Java string
- Count Number of Lowercase Characters in a String in Python Program
- Python Program to Count Number of Lowercase Characters in a String
- Program to count number of distinct characters of every substring of a string in Python
- How to count the number of repeated characters in a Golang String?
- How to count the number characters in a Java string?
- Program to count number of unique palindromes we can make using string characters in Python
- Count of elements matching particular condition in Python
- Finding count of special characters in a string in JavaScript
- Program to count number of palindromes of size k can be formed from the given string characters in Python
- Python Program to Calculate the Number of Words and the Number of Characters Present in a String
- Program to count number of characters in each bracket depth in Python
- Python program to count the number of spaces in string
- How to Count the Number of Vowels in a string using Python?
- Counting the number of redundant characters in a string - JavaScript

Advertisements