如何修复我的代码,以使列表索引不超出范围?

时间:2019-10-01 00:27:06

标签: python

从本质上讲,除一个示例外,我所有的示例均有效。我不知道如何解决。

def get_nth_tweet(desiredpost: str, stringwanted: int) -> str:
    """This function should return the nth valid tweet in the sequence 
    of tweets.
    Precondition: n >= 0
    >>>get_nth_tweet('If the Easter Bunny and the Tooth Fairy had babies would they take your teeth and leave chocolate for you?', 0)
    return ('If the Easter Bunny and the Tooth Fairy had babies')
    >>>get_nth_tweet('If the Easter Bunny and the Tooth Fairy had babies would they take your teeth and leave chocolate for you?', 23)
    return (' ')
    """
    n = 50
    nth1 = [(desiredpost[i:i+n]) for i in range(0, len(desiredpost), n)]
    if stringwanted <= len(nth1):
        return nth1[stringwanted]
    else:
        return ' '

回溯(最近通话最近):   在testGetNthTweet中的第46行,文件“ x-wingide-python-shell:// 4600183936/2”   _check中的文件“ x-wingide-python-shell:// 4600183936/2”,第72行 AssertionError:错误为非真:调用get_nth_tweet(abcdef,1)导致错误:列表索引超出范围

1 个答案:

答案 0 :(得分:-1)

将第12行替换为

if stringwanted < len(nth1):