Skip to content
Advertisement

Find common characters between two strings

I am trying to print the common letters from two different user inputs using a for loop. (I need to do it using a for loop.) I am running into two problems: 1. My statement “If char not in output…” is not pulling unique values. 2. The output is giving me a list of individual letters rather than a single string. I tried the split the output but split ran into a type error.

JavaScript

Advertisement

Answer

You are trying to perform the Set Intersection. Python has set.intersection method for the same. You can use it for your use-case as:

JavaScript

set will return the unique characters in your string. set.intersection method will return the characters which are common in both the sets.


If for loop is must for you, then you may use a list comprehension as:

JavaScript

Above result could also be achieved with explicit for loop as:

JavaScript
Advertisement