Python函数错误字符串索引超出范围

时间:2014-09-28 00:50:43

标签: python python-3.x

所以我要找出这段代码有什么问题,显然我没有看到任何错误,因为我刚刚开始学习python。

此外,当我运行该功能时,它会给我一个错误"String Index out of range"

我要测试这是否有用。

那么看起来有什么不对,我应该如何测试呢?

def is_reverse_of( st1, st2 ):

    """
    is_reverse_of : String String -> Boolean
    is_reverse_of tells if one string is the reverse of another.
    preconditions: st1 and st2 are character strings.
    """
    if len( st1 ) != len( st2 ):
        return False
    i = 0
    j = len( st2 )
    while j > 0:
        if st1[i] != st2[j]:
            return False
        else:
            i += 1
            j -= 1

    return True

这是我到目前为止进行测试的原因

def test_is_reverse_of():

    """
    a suite of pass/fail test cases to validate that is_reverse_of works.
    """
    # Complete this test function.
    st1 = str(input("Enter the string: "))
    st2 = str(input("Enter the string: "))

    is_reverse_of(st1, st2)

1 个答案:

答案 0 :(得分:1)

索引从0开始,因此从0到len(str2) - 1,而不是len(str2)。只需执行以下操作即可轻松解决问题:

j = len( st2 ) - 1

顺便说一句,你真的只需要一个索引,即eitehr i或j,因为另一个索引可以很容易地计算出来:

def is_reverse_of( st1, st2 ):
    if len( st1 ) != len( st2 ):
        return False
    l = len(st1)    
    for i in range(0, l):
        if st1[i] != st2[l - 1 - i]:
            return False
    return True