如何修复 'String index out of range' 错误
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: 字符串索引超出范围
更新:将 len(seq) 更改为 len(seq)-1 后,不再有字符串索引错误,但代码仍然无效。
输入:aaaagggggtt
Output: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)
我正在尝试编写一个代码,用一个符号及其重复次数替换字符串中的重复符号(例如:"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: 字符串索引超出范围
更新:将 len(seq) 更改为 len(seq)-1 后,不再有字符串索引错误,但代码仍然无效。
输入:aaaagggggtt
Output: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)