Cover Image for Python Program to Count the Number of Matching Characters in a Pair of String
204 views

Python Program to Count the Number of Matching Characters in a Pair of String

You can count the number of matching characters in a pair of strings in Python by iterating through the characters of one string and checking if each character exists in the other string. Here’s a Python program to do that:

def count_matching_characters(str1, str2):
    # Initialize a set to store unique matching characters
    matching_chars = set()

    # Iterate through the characters in the first string
    for char in str1:
        # Check if the character exists in the second string
        if char in str2:
            matching_chars.add(char)

    return len(matching_chars)

# Input two strings
string1 = input("Enter the first string: ")
string2 = input("Enter the second string: ")

# Count the number of matching characters
count = count_matching_characters(string1, string2)

# Display the result
print(f"Number of matching characters: {count}")

In this program:

  1. We define a function count_matching_characters that takes two strings as input.
  2. We initialize a set matching_chars to store unique matching characters.
  3. We iterate through the characters in the first string (str1) using a for loop.
  4. Inside the loop, we check if the character exists in the second string (str2) using the in operator. If it does, we add it to the matching_chars set.
  5. Finally, we return the length of the matching_chars set, which represents the count of unique matching characters.
  6. In the main part of the program, we input two strings from the user, call the count_matching_characters function to count the matching characters, and display the result.

This program will count the number of matching characters between the two input strings, considering each character only once (ignoring duplicates).

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS