- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements