Find common characters between two strings
Solution 1
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:
>>> word_1 = 'one'
>>> word_2 = 'toe'
# v join the intersection of `set`s to get back the string
# v v No need to type-cast it to `set`.
# v v Python takes care of it
>>> ''.join(set(word_1).intersection(word_2))
'oe'
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:
>>> unique_1 = [w for w in set(word_1) if w in word_2]
# OR
# >>> unique_2 = [w for w in set(word_2) if w in word_1]
>>> ''.join(unique_1) # Or, ''.join(unique_2)
'oe'
Above result could also be achieved with explicit for
loop as:
my_str = ''
for w in set(word_1):
if w in word_2:
my_str += w
# where `my_str` will hold `'oe'`
Solution 2
For this kind of problem, you're probably better off using sets:
wrd = 'one'
sec_wrd = 'toe'
wrd = set(wrd)
sec_wrd = set(sec_wrd)
print(''.join(sorted(wrd.intersection(sec_wrd))))
Related videos on Youtube
JMatth
Updated on July 10, 2022Comments
-
JMatth almost 2 years
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.wrd = 'one' sec_wrd = 'toe' def unique_letters(x): output =[] for char in x: if char not in output and char != " ": output.append(char) return output final_output = (unique_letters(wrd) + unique_letters(sec_wrd)) print(sorted(final_output))
-
Moinuddin Quadri about 6 yearswhat is your expected result for above code?
-
RomanPerekhrest about 6 years@JessMatthews, and why
n
andt
are thrown away as non-unique? -
Arnav Borborah about 6 yearsYou are looking for letters that are in both strings?
-
RomanPerekhrest about 6 years@JessMatthews, perhaps, change your title and question to: "find common items between 2 lists"
-
-
JMatth about 6 yearsI appreciate it. I need to use a for loop. I have tried to use intersection in the loop, but haven't gotten that to work.
-
JMatth about 6 yearsGreat! When I convert the inputs using .lower (to avoid user input errors) I am getting an error in the list comprehension line. Any idea why?
-
Moinuddin Quadri about 6 years@JessMatthews Do you mean
.lower()
??