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

2024-10-01 11:33:48 发布

您现在位置: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 ' '

回溯(最近一次呼叫): 文件“x-wingide-python-壳牌://4600183936/2,第46行,在testGetNthTweet中 文件“x-wingide-python-壳牌://4600183936/2“,第72行,在支票中” AssertionError:False不是true:调用get\n th\u tweet(abcdef,1)导致错误:列表索引超出范围


Tags: andthegetreturniftweetbunnyhad