【问题标题】:str.replace gives s[i-1] out of range error [duplicate]str.replace 给出 s[i-1] 超出范围错误 [重复]
【发布时间】:2018-04-08 04:26:46
【问题描述】:
import sys

def super_reduced_string(s):   
    i=len(s)-1  
    while(i>0):  
        if(s[i]==s[i-1]):
            s=s.replace(s[i],'')
            s=s.replace(s[i-1],'')
            i=len(s)-1
        else:
            i-=1
    return (s)

例如,如果我取一个字符串"aaabccddd",那么i 的值一开始就是8。我的if 语句为真,因此字符串变为'aaabccdd'

然后我想删除s[i-1] (s[7]) 然后你的字符串应该变成"aaabccd"

为什么会引发IndexError 异常,说s[i-1] 超出范围?

【问题讨论】:

  • s.replace(s[i],'') 并不意味着“替换 ith 字符”。如果ith 字符为'd',则表示“替换所有'd's”。
  • 提示:你想做的不是replace

标签: python python-3.x


【解决方案1】:

您正在删除多个字符str.replace() 查找给定字符串的 所有 次出现并替换它们。 s[8]'d',因此您从字符串中删除了 all 'd' 字符:

>>> s = 'aaabccddd'
>>> i = len(s) - 1
>>> i
8
>>> s.replace(s[i], '')
'aaabcc'

现在 s 只有 6 个字符长,所以 s[i-1]s[7] 超出范围。

如果您只想从字符串中删除 一个 字符,请不要使用 str.replace();你必须使用切片:

s = s[:i - 1] + s[i + 1:]  # remove the doubled character found

切片总是成功的,它永远不会抛出IndexError,但会产生一个空字符串。

工作代码(加入一些 PEP-8 空格):

def super_reduced_string(s):   
    i = len(s) - 1 
    while i:  
        if s[i] == s[i-1]:
            s = s[:i - 1] + s[i + 1:]
            i = len(s) - 1
        else:
            i -= 1
    return s

这会产生:

>>> super_reduced_string('aaabccddd')
'abd'

【讨论】:

  • 很高兴能帮上忙!如果您觉得它对您有用,请随时 accept my answer。 :-)
猜你喜欢
  • 2021-02-16
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
  • 2016-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多