3 回答
TA贡献1799条经验 获得超6个赞
您可以使用 aregex来查找 char ( ) 的重复(\w)\1+,然后获取匹配的位置(使用m.start()和m.end())
values = ['aaabca', 'helllooo', 'hellooo', 'abcd']
for value in values:
m = re.search(r'(\w)\1+', value)
if m:
print(f'{value:10s}{str((m.start(), m.end() - 1)):10s}{m.group(0)}')
else:
print(f'{value:10s}{str((-1, -1)):10s}')
给予
aaabca (0, 2) aaa
helllooo (2, 4) lll
hellooo (2, 3) ll
abcd (-1, -1)
笔记
要更改搜索重复项的字符类型,请替换\w
(\d)\1+
重复一个数字(.)\1+
任何字符的重复([a-z])\1+
重复小写字母...
TA贡献2016条经验 获得超9个赞
这是一种方法
x = "helllooo"
count = 0
start = -1
end = -1
for i in range(len(x)-1):
if x[i] == x[i+1]:
if count == 0:
start = i
count += 1
end = start + count
else:
if count > 0:
break
count = 0
print(start, end)
TA贡献1860条经验 获得超9个赞
word_list=['aaabca','helllooo','hellooo','abcd']
def find(word):
first_char=[]
index_list=[]
for n,i in enumerate(word):
if n+1<len(word):
if i==word[n+1]:
first_char.append(i)
while first_char[0]==i:
index_list.append(n)
index_list.append(n+1)
break
try:
print(index_list[0],index_list[-1])
except:
print(-1,-1)
for word in word_list:
find(word)
添加回答
举报