PYTHON IndexError:字符串索引超出范围

时间:2014-04-12 12:20:05

标签: python

问题陈述:编写一个名为censor的函数,它将两个字符串(文本和单词)作为输入。它应该返回带有您选择用星号替换的单词的文本

这是我的代码,

def censor(text, word):
    i = 0
    j = 0
    ans = ""

    while i<len(text):
        while text[j] == word[j]:
            j = j + 1
        if text[j+1] == " " or j+1 == len(text):
            while i<j:
                ans += "*"
                i = i + 1
            ans += " "
            i = i + 1
        else:
            while text[j] != " ":
                j = j + 1
            while i<=j:
                ans += text[i]
                i = i + 1

        i = i + 1
        j = j + 1

    return ans

print censor("how are you? you are not fine.","you")

但是我收到以下错误,

Traceback (most recent call last):
  File "python", line 27, in <module>
  File "python", line 7, in censor
IndexError: string index out of range

2 个答案:

答案 0 :(得分:1)

这比它需要的要复杂得多。你可以这样做:

def censor(text, censored_word):
    return text.replace(censored_word, '*'*len(censored_word))

>>> censor('How are you? Are you okay?', 'you')
'How are ***? Are *** okay?'

如果您不希望对youth这个词进行审查,但您希望审核you,请按以下步骤操作:

def censor(text, censored_word):
    repl = '*'*len(censored_word)
    return ' '.join([repl if word == censored_word else word for word in text.split()])

如果您想要多个删失字词:

def censor(text, censored_words):
    return ' '.join(['*'*len(word) if word in censored_words else word for word in text.split()])

在处理索引错误时,打印索引通常会有所帮助,并找出索引的值不在所需范围内的原因。

答案 1 :(得分:0)

在python中使用string replace来替换字符串是很好的。 在您的情况下,您应该使用单词的长度来匹配文本中的单词:

def censor(text, word):
    i = 0
    j = 0
    ans = ""
    wl=len(word)

    while i<(len(text)):
        if word==text[i:i+wl]:
            ans=ans+'*'*wl
            i=i+wl
        else:
            ans=ans+text[i]
            i = i + 1

    return ans

print censor("how are you? you are not fine.","you")