簡體   English   中英

我不明白為什么這個字符串索引在Python中超出范圍

[英]I don't see why this string index is out of range in 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”作為參數,我會發現等於“ length-1”的“ end”將阻止索引超出范圍。

有什么幫助嗎?

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

end = len(str)

順便說一句,如果您想遍歷每個數字:

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

還有更多的pythonic:

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

基於文檔字符串

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

我只想使用模運算符%提供另一種方法來測試可分類性:

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))

我看到幾個問題:

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])

end不是length-1 ; 它是s[length-1] ,也就是字符串s的最后一個字符。 當您使用'25'調用該函數時,由於字符串中沒有5個字符,因此會出現IndexError 另外,由於s已經是字符串,因此無需執行str(s)

順便說一下,要完成您的文檔字符串所說的,您需要檢查總和是否被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
def divisible_by_3(s):
    try:
        return int(s) % 3 == 0
    except:
        return False

達到功能目標的一種簡單方法就是這樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM