Python program to remove words that are common in two Strings

When it is required to remove words that are common in both the strings, a method is defined that takes two strings. The strings are spit based on spaces and list comprehension is used to filter out the result.


Below is a demonstration of the same

def common_words_filter(my_string_1, my_string_2):
   my_word_count = {}

   for word in my_string_1.split():
      my_word_count[word] = my_word_count.get(word, 0) + 1

   for word in my_string_2.split():
      my_word_count[word] = my_word_count.get(word, 0) + 1

   return [word for word in my_word_count if my_word_count[word] == 1]

my_string_1 = "Python is fun"
print("The first string is :")

my_string_2 = "Python is fun to learn"
print("The second string is :")

print("The result is :")
print(common_words_filter(my_string_1, my_string_2))


The first string is :
Python is fun
The second string is :
Python is fun to learn
The uncommon words from the two strings are :
['to', 'learn']


  • A method named ‘common_words_filter’ is defined that takes two strings as parameters.

  • An empty dictionary is defined,

  • The first string is split based on spaces and iterated over.

  • The ‘get’ method is used to get the word and the specific index.

  • The same is done for the second string.

  • The list comprehension is used to iterate through the dictionary and check if the word count is 1 or not.

  • Outside the method, two strings are defined and are displayed on the console.

  • The method is called by passing the required parameter.

  • The output is displayed on the console.

Updated on: 21-Sep-2021


Kickstart Your Career

Get certified by completing the course

Get Started