所以我要找出这个代码有什么问题,显然我没有看到任何错误,因为我刚刚学习了python。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)
检查'[j]'索引政策。尝试访问长度为len(aString)== j'的字符串的第j个元素失败,因为索引是从零开始的---'aString [0]'...'aString [len-1 ]' – user3666197 2014-09-28 01:02:07
'input'已经是一个字符串,所以不需要转换和'如果st1 [i]!= st2 [j-1]:'将解决你的索引错误 – 2014-09-28 01:09:16