Reputation: 247
Straight to the point: I am wanting to print every instance of these characters in a string. For example:
#Pseudocode below
animals = 'cat dog fish goat pig'
if 'abcd' in animals,
print(instanceOfIt)
would spit out
cada
*letters in cat
, dog
and goat
How would I accomplish this?
Upvotes: 0
Views: 31
Reputation: 27283
If I understand you correctly:
animals = 'cat dog fish goat pig'
print(''.join(filter(lambda x: x in 'abcd', animals)))
filter
takes a function and an iterable, and returns a new iterable that contains only those elements for which the function returned something truthy.
A lambda expression is like an inline function, it would be equivalent to writing myfunction
there and defining it earlier like this:
def myfunction(x):
return x in 'abcd'
print(''.join(filter(myfunction, animals)))
Alternatively (thanks, Peter Wood):
print(''.join(filter('abcd'.__contains__, animals)))
Upvotes: 1