Find Characters that are Common to Two Strings in Python

Find Characters that are Common to Two Strings

To find characters that are present in both the given strings, create set objects using the given strings, then use Set Intersection Operator (&) with the two set objects passed as operands.

Given two strings: str1, and str2; the expression to find the characters that are common to both the strings str1 and str2 is

set(str1) & set(str2)

Examples

1. Find character common to given two strings

In the following example, we take two strings in str1 and str2, and find the characters that are common to both the strings str1 and str2.

Python Program

set1 = set('apple')
set2 = set('banana')
output = set1 & set2
print(output)
Run Code Copy

Output

{'a'}

We can use the same expression to find the characters that are common to more than two strings.

2. Find character common to given three strings

In the following program, we take three strings in str1, str2, and str3, and find the characters that are common to these three strings.

Python Program

set1 = set('apple is better')
set2 = set('banana')
set3 = set('baby')
output = set1 & set2 & set3
print(output)
Run Code Copy

Output

{'b', 'a'}

Summary

In this tutorial of Python Examples, we learned how to find the characters that are common to given strings using Set Intersection.

Related Tutorials

Code copied to clipboard successfully 👍