Find common words in two strings using Python

  • Sample code snippet to find the common characters or words in two given strings excluding spaces. Implemented using built-in string methods in Python.

  • Common characters in two strings

    To find common characters in two strings, we first fetch the unique characters in each by converting these to sets.
    Then do a comparison within a loop to identify matching characters.

    Copied
    str1 = 'This is a test string'
    str2 = 'This is another string'
    
    str1 = str1.lower().replace(" ", "")
    str2 = str2.lower().replace(" ", "")
    
    charsinstr1 = list(set(str1.strip()))
    charsinstr2 = list(set(str2.strip()))
    
    commonchars = []
    for c in charsinstr1:
        if (c in charsinstr2):
            commonchars.append(c)
    
    print(commonchars)
    print(len(commonchars))
    
    Output:
      ['s', 'h', 'g', 'a', 'i', 'r', 'n', 'e', 't']
      9
  • Common words in two strings

    Here, we will first convert the string to a list of words using split function.
    Then loop through each word and compare.

    Copied
    str1 = 'This is a test string'
    str2 = 'This is another string'
    
    wordsinstr1 = str1.lower().split()
    wordsinstr2 = str2.lower().split()
    
    commonwords = []
    for word in wordsinstr1:
        if (word in wordsinstr2):
            commonwords.append(word)
    
    print(commonwords)
    print(len(commonwords))
    
    Output:
      ['this', 'is', 'string']
      3

    Another easy way is to use list comprehension without using the for loop.
    Sample below.

    Copied
    str1 = 'This is a test string'
    str2 = 'This is another string'
    
    commonwords = [ w for w in str1.lower().split() if (w in str2.lower().split()) ]
    print(commonwords)
    print(len(commonwords))
    
    Output:
      ['this', 'is', 'string']
      3
Absolute Code Works - Python Topics