'search for list items within a string
I know i can search for list items within a string like this:
values = ['XX', 'ZI']
if any(val in my_string for val in values):
print('priting', my_string )
However, in this way, I cannot access the list values after the if statement. I want to print the valuewhich is present within the my_string as well. How can I achieve this?
Solution 1:[1]
I can see at least two solutions to that.
The first is using a loop, as told in the comments:
my_string = 'Test XX'
values = ['XX', 'ZI']
for val in values:
if val in my_string:
print(val)
Another solution would be to use filter() to get the list of matches
my_string = 'Test XX'
values = ['XX', 'ZI']
matches = filter(lambda val: val in my_string, values)
print(list(matches))
Solution 2:[2]
You could use a regex approach here:
my_string = "Bacardi XX Rum and ZIP codes"
values = ['XX', 'ZI', 'QQ']
regex = r'(' + r'|'.join([re.escape(x) for x in values]) + r')'
matches = re.findall(regex, my_string)
print(matches) # ['XX', 'ZI']
Here we build an alternation of values, then do an exhaustive regex search for each value against the input string. Only matching values will be captured and printed at the end.
Solution 3:[3]
You can use the string function, find() to do the task.
matching_strings = filter(lambda val : string.find(val,0,len(string)) != -1,values)
print(list(matching_strings))
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 | jkoestinger |
| Solution 2 | |
| Solution 3 | Deepeshkumar |
