What\'s the easiest way to check if a string only contains certain specified characters in Python? (Without using RegEx or anything, of course)
Specifically, I have
Something like this:
strings = ['aba', 'acba', 'caz']
given = "abc"
filter(lambda string: all(char in given for char in string), strings)
Assuming the discrepancy in your example is a typo, then this should work:
my_list = ['aba', 'acba', 'caz']
result = [s for s in my_list if not s.strip('abc')]
results in ['aba', 'acba']
. string.strip(characters) will return an empty string if the string to be stripped contains nothing but characters in the input. Order of the characters should not matter.
You can make use of sets:
>>> l = ['aba', 'acba', 'caz']
>>> s = set('abc')
>>> [item for item in l if not set(item).difference(s)]
['aba', 'acba']
Assuming you only want the strings in your list which have only the characters in your search string, you can easily perform
>>> hay = ['aba', 'acba', 'caz']
>>> needle = set('abc')
>>> [h for h in hay if not set(h) - needle]
['aba', 'acba']
If you wan't to avoid sets, you can also do the same using str.translate. In this case, you are removing all characters which are in your search string.
>>> needle = 'abc'
>>> [h for h in hay if not h.translate(None,needle)]
['aba', 'acba']
I will assume your reluctance for regexp is not really an issue :
strings = ['aba', 'acba', 'caz']
given = "abc"
filter(lambda value: re.match("^[" + given + "]$", value), strings)
Below is the code:
a = ['aba', 'acba', 'caz']
needle = 'abc'
def onlyNeedle(word):
for letter in word:
if letter not in needle:
return False
return True
a = filter(onlyNeedle, a)
print a