字符串中符号的起始和结束位置



我试图找到_在字符串中作为元组列表的开始和结束位置。

我使用的代码是
sentence = 'special events _______ ______ ___ _______ ____ _____ _______ ___________ brochure subscriptions ticket guide'
symbol = '_'
position = [(match.start(),match.end()) for match in re.finditer(symbol, sentence)]

得到的输出是

[(15, 16), (16, 17), (17, 18), (18, 19), (19, 20)..................]

如何将连续定位符号的起始和结束位置作为元组列表。

您应该添加+量词。由于symbol可能是正则表达式的特殊符号,您可能需要用re.escape转义它。

import re
sentence = 'special events _______ ______ ___ _______ ____ _____ _______ ___________ brochure subscriptions ticket guide'
symbol = '_'
needle = f'{re.escape(symbol)}+'
position = [(match.start(),match.end()) for match in re.finditer(needle, sentence)]
print(position)

结果为[(15, 22), (23, 29), (30, 33), (34, 41), (42, 46), (47, 52), (53, 60), (61, 72)]

请注意endMatch.end文档中所述的匹配后的位置。

你可以这样做:

sentence2 = ' ' + sentence[:-1]
starts = [i for i in range(len(sentence))if sentence[i] == '_' and sentence2[i] != '_' ]
ends = [i - 1 for i in range(len(sentence)) if sentence2[i] == '_' and sentence[i] != '_']
pairs = list(zip(starts, ends))
print(pairs)

输出:

[(15, 21), (23, 28), (30, 32), (34, 40), (42, 45), (47, 51), (53, 59), (61, 71)]

这将给出一个或多个连续符号字符的子字符串中symbol的第一个和最后一个实例的索引。如果您需要使用python切片语义的结果(start ==连续子串中符号的第一个实例的索引,end ==紧接该子串中符号的最后一个实例的索引),您可以在ends的初始化行中将i - 1更改为i

最新更新