【发布时间】:2018-04-19 15:52:22
【问题描述】:
我有一个看起来像这样的字符串列表:
list_strings = ["The", "11:2dog", "is", "2:33", "a22:11", "german", "shepherd.2:2"]
这是我想做的:
对于列表中的每个字符串,我想删除与模式
number:number匹配的数字。此模式将始终位于字符串的开头或结尾。当模式从字符串中删除时,如果它在末尾,我想将它作为列表的下一个元素插入,如果它在开头,我想作为列表的前一个元素字符串。
所以:
list_strings = ["The", "11:2dog", "is", "2:33", "a22:11", "german", "shepherd.2:2"]
变成:
new_list_strings = ["The", "11:2", "dog", "is", "2:33", "a", "22:11", "german", "shepherd.", "2:2"]
为了找到可能包含该模式的单词,我尝试使用正则表达式:
for index, word in enumerate(list_strings):
try:
if re.search(r'\d+:\d+', word).group() != None:
words_with_pattern.append([index], word)
except:
pass
但是,这只查找模式单独的实例,例如“11:21”。一旦我有了一个包含该模式的所有单词的列表,我将不得不从字符串中删除该模式,注意它是在开头还是结尾,并将其插入到列表中的相应索引处。
有什么帮助吗?谢谢!
【问题讨论】:
标签: python regex string python-3.x text