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:
common_chars.add(char)
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))
else:
print("No common characters found.")How It Works:
- The program defines a function
find_common_charactersthat takes two input stringsstr1andstr2as arguments. - It initializes an empty set called
common_charsto store the common characters found. - The program iterates through each character in
str1. If the character is also present instr2, it adds the character to thecommon_charsset. - After iterating through all characters in
str1, the program returns the set of common characters. - The program then takes user input for two strings,
input_str1andinput_str2. - It calls the
find_common_charactersfunction with the input strings and stores the result in thecommon_charactersvariable. - 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.
Input/Output:
