Python Practice › String Programs › Program 23

Common words in two strings

EasyString Programs · 23 of 106

Write a Python program to find the words that appear in both strings, ignoring punctuation.

Advertisement
Input
"Very Good Morning, How are You" and "You are a Good student, keep it up"
Output
['Good', 'You', 'are']

Approach

  1. Strip punctuation, split into sets, and intersect.

Solution

Python
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.

More string programs

← All 106 String Programs

Leave a Comment