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

2024-09-29 01:38:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: theto字符串元素park列表outputtoday
2条回答

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

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']

您可以使用正则表达式,对任何单词进行拆分,并将拆分结果放入一个组中,以便将其保留在输出中。我们还可以使用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']

相关问题 更多 >