Split string by char if followed by any value in list

Viewed 36

How do I accomplish to split a string by X, only if X is followed by any of the values in a list?

Split below by , if next word is in list

first_string = "color=blue,size=xl" # Should be splitted 
second_string = "color=white,pattern=dotted" # Should not be splitted
list = ['size', 'weather', 'mode'];
1 Answers
first_string = "color=blue,size=xl" # Should be splitted 
second_string = "color=white,pattern=dotted" # Should not be splitted
lst = ['size', 'weather', 'mode']

You can check with a for-loop whether you have the value in list. Also make sure you do not use list name as a variable name.

k=[]
for x in lst:
  if x in first_string:
    k.append(first_string.split(x))
#output
[['color=blue,', '=xl']]

This was split since size was present in the original list. Similarly, if you would try the same code with the second string it will not split as there are no common values.

Related