You can do it as follows without using re
Obviously using re would be more efficient, this answer should demonstrate that you can do it with split()
[EDITED based on comment]
my_string = "foo [[ram doo]] bar [[very cool]]" # also works for the following strings #my_string = "foo [[ram doo]] bar [[very cool]] something else" #my_string = "something else" #my_string = "foo bar [[ram doo]]" ##<-- this is the border case #my_string = "[[ram doo]] foo bar" #my_string = "foo [[ram doo]] bar " # set "splitting string" s1 = ']]' s2 = '[[' if my_string[-2::] == ']]' and my_string.count(']]') == 1: # reverse splitting string for border case s1 = '[[' s2 = ']]' # split on s1 only if s1 in string my_list1 = [a if s1 in my_string else my_string for a in my_string.split(s1)] # split each element on s2 or space my_list2 = [x.split(s2) if s2 in x else x.split(' ') for x in my_list1] # flatten lists in lists, and strip spaces my_list3 = [a.strip(' ') for b in my_list2 for a in (b if isinstance(b, list) else [b])] # get rid of empties my_list4 = [a for a in my_list3 if a != ''] print(my_list4) # will output # ['foo', 'ram doo', 'bar', 'very cool']
So the conclusion is to use re
source share