VOOZH about

URL: https://www.geeksforgeeks.org/dsa/python-program-to-remove-words-that-are-common-in-two-strings/

⇱ Remove Words that are Common in Two Strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove Words that are Common in Two Strings

Last Updated : 23 Jul, 2025

We are given two strings we need to remove words that are common in two strings. For example, we are having two strings s = "hello world programming is fun" a = "world is amazing programming" we need to remove the common words from both the string so that output should be "hello fun amazing" we can use multiple methods for this like set operations list comprehension.

Using Set Operations

Set operations find common words using intersection (&), and list comprehension removes those words from both strings.


Output
hello fun
amazing

Explanation:

  • Code splits both input strings s and a into sets of words (w and b) then finds the common words using the set intersection (&), storing them in c.
  • It then reconstructs the strings res1 and res2 by joining the words from the original strings that are not in the common words set (c)

Using List Comprehension with a Set

List comprehension filters out common words by checking if each word in the original strings is not in the set of common words. The result is a new string created by joining the remaining words


Output
hello fun
amazing

Explanation:

  • Code splits string b into a set of words (w) then uses list comprehension to remove any words from a that are present in w and stores the result in res1.
  • Similarly it removes words from b that are found in a and stores the result in res2 then prints both results.

Using collections.Counter

Using collections.Counter the code counts the word frequencies in both strings, finds common words with set intersection (&) and removes them using list comprehension to form the updated strings.


Output
hello fun
amazing

Explanation:

  • Code splits both strings a and b into word lists counts the frequency of each word using Counter and finds the common words using set intersection.
  • It then removes the common words from both strings and joins the remaining words to form the resulting strings res1 and res2 which are printed.
Comment