I'm trying to determine if any characters from a string1 are in another string2
example:
string1 = "abcdefghijklmnopqrstuvwxyz"
any of the characters from this string1 are in this string2 for example:
string2="HELLO WoRLD"
but i want to do so without using any loops, is there anything that can be done in python maybe using the in statement
CodePudding user response:
You can do it using sets
str1 = 'abcd'
str2 = 'bcde'
set1 = set(str1)
set2 = set(str2)
if set1.intersection(set2):
print('There are same chars in the strings')
CodePudding user response:
For this example, you can use set.intersection:
out = list(set(string1).intersection(string2))
Output:
['o']
CodePudding user response:
you could do something like this:
string1 = "abcdefghijklmnopqrstuvwxyz"
string2="HELLO WoRLD"
#define a list that will contain the characters in common
chars_in_common = []
for char in string1:
#looping trough the string to find characters that are in common
if char in string2:
# updating list
chars_in_common.append(char)
print(chars_in_common)
Output:
['o']
