如何修复'String index out of range'错误 [英] How to fix 'String index out of range' error

查看:776
本文介绍了如何修复'String index out of range'错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个代码,该代码用一个符号及其重复次数替换字符串中的重复符号(例如:"aaaaggggtt"->"a4g4t2").但是我的字符串索引超出范围错误((

I am trying to write a code which replaces repeating symbols in a string with a symbol and number of its repeats (like that: "aaaaggggtt" --> "a4g4t2"). But I'm getting string index out of range error((

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:字符串索引超出范围

line 6, in if seq[i] == seq[j]: IndexError: string index out of range

UPD:将len(seq)更改为len(seq)-1之后,不再有字符串索引错误,但是代码仍然无法正常工作. 输入:aaaaggggtt
输出:aaaaggggtt(相同)

UPD: After changing len(seq) to len(seq)-1 there is no more string index error, but the code still doesn't work. Input: aaaaggggtt
Output:aaaaggggtt (same)

推荐答案

您可以遍历字符串,保持运行中的计数器并在创建过程中创建字符串

You can iterate over the string, keeping a running counter and create your string as you go

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 来解决此问题.

Or you can approach this using 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

这篇关于如何修复'String index out of range'错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆