Python Forum

Full Version: is any character in s1 in s2
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i wrote a function to find if any character in string one is in string two. is there anything in Python to do this without that character loop or even better, without making a function?
Use sets.
perhaps sets makes the logic work better. but i get strings as my data source. how do you suggest that i use sets?
(Aug-26-2024, 01:57 AM)Skaperen Wrote: [ -> ]perhaps sets makes the logic work better. but i get strings as my data source. how do you suggest that i use sets?

>>> string1 = "some characters"
>>> string2 = "other characters"
>>> string3 = "bwgfz"
>>> bool(set(string1) & set(string2))
True
>>> bool(set(string1) & set(string3))
False
Just add the strings, then do the magic? I presumed you want to keep the common letters.

from string import ascii_letters

string1 = ascii_letters[0:10]
string2 = ascii_letters[5:15]
string3 = string1 + string2
# if there is overlap, len(res) will be < len(string3), (< 20 here)
res = ''.join(sorted(list(set(string3))))
len(res) # 15
OP - Back to your original question, are you wanting to know IF there are duplicate characters (yes/no which is well answered here) or WHAT characters are duplicated?
(Aug-26-2024, 02:50 PM)jefsummers Wrote: [ -> ]OP - Back to your original question, are you wanting to know IF there are duplicate characters (yes/no which is well answered here) or WHAT characters are duplicated?

i want to know IF ... if i recall the project, now.