Check if any character in one string appears in another

Question:

I have a string of text

hfHrpphHBppfTvmzgMmbLbgf

I have separated this string into two half’s

hfHrpphHBppf,TvmzgMmbLbgf

I’d like to check if any of the characters in the first string, also appear in the second string, and would like to class lowercase and uppercase characters as separate (so if string 1 had a and string 2 had A this would not be a match).

and the above would return:

f
Asked By: Conor

||

Answers:

split_text = ['hfHrpphHBppf', 'TvmzgMmbLbgf']

for char in split_text[0]:
    if char in split_text[1]:
        print(char)

There is probably a better way to do it, but this a quick and simple way to do what you want.

Edit:

split_text = ['hfHrpphHBppf', 'TvmzgMmbLbgf']
found_chars = []

for char in split_text[0]:
    if char in split_text[1] and char not in found_chars:
        found_chars.append(char)
        print(char)

There is almost certainly a better way of doing this, but this is a way of doing it with the answer I already gave

Answered By: tygzy

You could use the "in" word.

something like this :

for i in range(len(word1) : 
   if word1[i] in word2 : 
      print(word[i]) 

Not optimal, but it should print you all the letter in common

Answered By: Pierre Marsaa

You can achieve this using set() and intersection

text = "hfHrpphHBppf,TvmzgMmbLbgf"
text = text.split(",")
print(set(text[0]).intersection(set(text[1])))
Answered By: Tr3ate

You can use list comprehension in order to check if letters from string a appears in string b.

a='hfHrpphHBppf'
b='TvmzgMmbLbgf'
c=[x for x in a if x in b]
print(' '.join(set(c)))

then output will be:

f

But you can use for,too. Like:

a='hfHrpphHBppf'
b='TvmzgMmbLbgf'
c=[]
for i in a:
  if i in b:
  c.append(i)
print(set(c))
Answered By: İlaha Algayeva
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.