'How to find if a string has a character which isn't in another string
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?
Solution 1:[1]
Solution 2:[2]
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
Solution 3:[3]
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'}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrej Kesely |
| Solution 2 | BrokenBenchmark |
| Solution 3 | Sharim Iqbal |
