Python Program to Find Common Characters in Two Strings

This Python program finds and displays the common characters present in two input strings.

Problem Statement:

Given two strings, we need to write a program that identifies and outputs the characters that are common in both strings.

Python Program to Find Common Characters in Two Strings

def find_common_characters(str1, str2):
    common_chars = set()
    for char in str1:
        if char in str2:
    return common_chars

# Input strings
input_str1 = input("Enter the first string: ")
input_str2 = input("Enter the second string: ")

common_characters = find_common_characters(input_str1, input_str2)

if common_characters:
    print("Common characters:", ', '.join(common_characters))
    print("No common characters found.")

How It Works:

  1. The program defines a function find_common_characters that takes two input strings str1 and str2 as arguments.
  2. It initializes an empty set called common_chars to store the common characters found.
  3. The program iterates through each character in str1. If the character is also present in str2, it adds the character to the common_chars set.
  4. After iterating through all characters in str1, the program returns the set of common characters.
  5. The program then takes user input for two strings, input_str1 and input_str2.
  6. It calls the find_common_characters function with the input strings and stores the result in the common_characters variable.
  7. If there are common characters, the program prints them out, separated by commas. If no common characters are found, it prints a message indicating that.