How to find if a string has a character which isn't in another string

430 Views Asked by At

For example I can have the string 'acagtcas' and I want to find if the string has any characters that aren't a, c, g or t. I've tried using not but I haven't been able to make it work. How can I implement this?

3

There are 3 best solutions below

0
On

You can use a comprehension to check the validity of each letter, and then use any() to see whether at least one of them is invalid:

valid_letters = 'acgt'
data = 'acagtcas'

any(letter not in valid_letters for letter in data)

Output:

True
0
On

You can use set.difference:

s = "acagtcas"

x = set(s).difference("acgt")
print(x)

Prints:

{'s'}
0
On
valid_letters = 'acgt'
data = 'acagtcas'

print(bool(set(data)-set(valid_letters)))

output:

True
valid_letters = 'acgt'
data = 'acagtcas'

print(set(data)-set(valid_letters))

Output:

{'s'}