我不明白为什么这个字符串索引在Python中超出范围

时间:2015-08-31 11:57:05

标签: python

我不明白为什么这会超出范围。

def divisible_by_3(s):
'''Returns True if the number represented by the string s is divisible by 3, False otherwise.'''

    length = len(str(s))
    end = s[length-1]
    sum = 0

    for x in range (0, int(end)):
        sum = sum + int(s[x])

    return sum

如果我输入“25”作为参数,我会认为'end'等于length-1会阻止索引超出范围。

任何帮助?

5 个答案:

答案 0 :(得分:4)

您的end不是最后一位数的索引,而是数字本身。可能你想要

end = len(str)

顺便说一下,如果你想迭代每个数字:

for digit in str:
    sum += int(digit)

更多pythonic:

return sum( int(digit) for digit in str )

答案 1 :(得分:1)

基于docstring

'''Returns True if the number represented by the string s is divisible by 3, False otherwise.'''

我只想提供另一种使用modulo operator %测试divisibiliy的方法:

def divisible_by_3(s):
    '''Returns True if the number represented by the string s is divisible by 3, False otherwise.'''
    try:
        integer = int(s)
    except Exception as e:
        raise e
    else:
        return True if integer % 3 == 0 else False


s = input('Please enter a number: ')
print(divisible_by_3(s))

答案 2 :(得分:0)

我看到几个问题:

def divisible_by_3(s):
    '''Returns True if the number represented by the string s is divisible by 3, False otherwise.'''

    length = len(str(s))
    end = s[length-1]

在这里,您要为s本身编制索引,而不是字符串。更好的方法是

    s_str = str(s)
    length = len(s_str)
    end = s_str[length-1]

如果你真的需要这个end

    for x in range (0, int(end)):
        sum = sum + int(s[x])

这里你应该做

    for x in range(0, length):
        sum += int(s_str[x])

答案 3 :(得分:0)

end不是length-1;它是s[length-1],a.k.a。字符串s的最后一个字符。当您使用'25'调用该函数时,由于字符串中没有5个字符,因此您获得IndexError。此外,由于str(s)已经是字符串,因此无需s

顺便说一句,要完成docstring所说的内容,你需要检查总和是否可以被3整除。

def divisible_by_3(s):
    length = len(s)
    end = length-1
    sum = 0

    for x in range(end+1):
        sum += int(s[x])

    return sum % 3 == 0

这是一种更好的方法:

def divisible_by_3(s):
    for digit in s:
        sum += int(digit)

    return sum % 3 == 0

更好:

def divisible_by_3(s):
    return sum(int(digit) for digit in s) % 3 == 0

当然你可以这样做:

def divisible_by_3(s):
    return int(s) % 3 == 0

答案 4 :(得分:0)

def divisible_by_3(s):
    try:
        return int(s) % 3 == 0
    except:
        return False

达到功能目标的简单方法可以是这样的。