![](/img/trans.png)
[英]How to fix 'string index out of range' error in a function that ciphers a string
[英]How to fix 'String index out of range' error
我正在嘗試編寫代碼,用符號和重復次數替換字符串中的重復符號(例如:“ aaaaggggtt”->“ a4g4t2”)。 但是我得到的字符串索引超出范圍錯誤((
seq = input()
i = 0
j = 1
v = 1
while j<=len(seq)-1:
if seq[i] == seq[j]:
v += 1
i += 1
j += 1
elif seq[i] != seq[j]:
seq.replace(seq[i-v:j], seq[i] + str(v))
v = 1
i += 1
j += 1
print(seq)
第6行,如果seq [i] == seq [j]:IndexError:字符串索引超出范圍
UPD:將len(seq)更改為len(seq)-1之后,不再出現字符串索引錯誤,但是代碼仍然無法正常工作。 輸入:aaaaggggtt
輸出:aaaaggggtt(相同)
您可以遍歷字符串,保持運行中的計數器並在運行時創建字符串
s = 'aaaaggggtt'
res = ''
counter = 1
#Iterate over the string
for idx in range(len(s)-1):
#If the character changes
if s[idx] != s[idx+1]:
#Append last character and counter, and reset it
res += s[idx]+str(counter)
counter = 1
else:
#Else increment the counter
counter+=1
#Append the last character and it's counter
res += s[-1]+str(counter)
print(res)
或者您可以使用itertools.groupby來解決這個問題
from itertools import groupby
s = 'aaaaggggtt'
#Count numbers and associated length in a list
res = ['{}{}'.format(model, len(list(group))) for model, group in groupby(s)]
#Convert list to string
res = ''.join(res)
print(res)
輸出將是
a4g4t2
簡單方法:
str1 = 'aaaaggggtt'
set1 = set(str1)
res = ''
for i in set1:
res+=i+str(str1.count(i))
print(res)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.