Python Practice › String Programs › Program 23
Common words in two strings
Write a Python program to find the words that appear in both strings, ignoring punctuation.
Input
"Very Good Morning, How are You" and "You are a Good student, keep it up"
Output
['Good', 'You', 'are']
Approach
- Strip punctuation, split into sets, and intersect.
Solution
s1 = "Very Good Morning, How are You"s2 = "You are a Good student, keep it up"w1 = {w.strip(",.") for w in s1.split()}w2 = {w.strip(",.") for w in s2.split()}print(sorted(w1 & w2))Output
['Good', 'You', 'are']
Line by line
Lines 3-4
strip(",.") removes punctuation stuck to a word, such as “Morning,”.
Line 5
& keeps the words present in both sets.
Learn the concept
New to this topic? Read the lesson, then come back.