Home > Software engineering >  search for list items within a string
search for list items within a string

Time:04-20

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?

CodePudding user response:

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))

CodePudding user response:

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.

CodePudding user response:

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))
  • Related