-1

Here is the list1, string and the list2 should be

list1 = ["NORTH", "SOUTH", "EAST", "WEST"]

and

string = NORTHSOUTHWESTEASTWEST

I want

list2 = ["NORTH", "SOUTH", "WEST", "EAST", "WEST"]
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Hàm Louis
  • 41
  • 7
  • Possible duplicates with https://stackoverflow.com/questions/54481198/python-match-multiple-substrings-in-a-string – mkrieger1 Apr 20 '23 at 10:45

2 Answers2

3

With regexp matching (via combining list1 items to regex pattern):

import re

list1 = ["NORTH", "SOUTH", "EAST", "WEST"]
string = 'NORTHSOUTHWESTEASTWEST'
res = re.findall(fr'{"|".join(list1)}', string)
print(res)

['NORTH', 'SOUTH', 'WEST', 'EAST', 'WEST']
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
2

You can use regular expressions.

For example:

import re 

list1 = ["NORTH", "SOUTH", "EAST", "WEST"]
s = "NORTHSOUTHWESTEASTWEST"

pattern = re.compile("(" + r"|".join(list1) + ")" )

print( pattern.findall(s))

Output:

['NORTH', 'SOUTH', 'WEST', 'EAST', 'WEST']
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Rakesh
  • 81,458
  • 17
  • 76
  • 113