如何解决如何从列表中的项目中拆分字符串?
我想根据列表中的元素拆分字符串,但是我不确定该怎么做。
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']
,
通过将每个元素用作my_list
的定界符来遍历str.split()
:
input = "IwenttotheParkToday".lower() # make sure the casing matches
my_list = ["went","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','park','today']
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。