Python 如何从列表中的项目中拆分字符串?

Python 如何从列表中的项目中拆分字符串?,python,string,list,split,Python,String,List,Split,我想根据列表中的元素分割字符串,但我不知道如何分割 string = "IwenttotheParkToday" my_list = ["went", "the", "today"] Desired Output: [I, went, to, the, park, today] 您可以使用正则表达式,对任何单词进行拆分,并将拆分结果放入一个组中,以便将其保留在输出中。我们还

我想根据列表中的元素分割字符串,但我不知道如何分割

    string = "IwenttotheParkToday"
    my_list = ["went", "the", "today"]
    
    Desired Output:
    [I, went, to, the, park, today]

您可以使用正则表达式,对任何单词进行拆分,并将拆分结果放入一个组中,以便将其保留在输出中。我们还可以使用
re.I
标志以不区分大小写的方式进行匹配:

import re

string = "IwenttotheParkToday"
my_list = ["went", "the", "today"]

# we split on any of the words in my_list, and put it into a group 
# so that it is included in the output
split_re = re.compile('(' + '|'.join(my_list) + ')', re.I)
# the regex we use will be '(went|the|today)'

# we remove empty words if one of the split strings was at the start or end
out = [word for word in split_re.split(string) if word]

print(out)
# ['I', 'went', 'to', 'the', 'Park', 'Today']

通过使用每个元素作为
str.split()的分隔符来循环
my_list


为什么这是期望的输出?(也就是说,从这些输入到输出的逻辑是什么。)你能演示一下解决这个问题的方法吗?这只是一个例子,我曾尝试使用re模块,但我无法将它与某种包含列表结合起来。为什么
I
是左大写的,而
Park
Today
不是?你可能想
re.escape()
列表中的每个条目都是更一般的情况。谢谢!修复了我的问题为什么使用正则表达式如此复杂?您的输出与(声明的)所需输出不匹配。@阿德里安:可能更快?您的输出与所需输出不匹配。
input = "IwenttotheParkToday".lower() # make sure the casing matches
my_list = ["went", "the", "today"]

result = []

for current_delimiter in my_list:
  first, input = input.split(current_delimiter, maxsplit=2)
  result.extend((first, current_delimiter))

print(result) # prints ['i', 'went', 'to', 'the', 'park', 'today']