Python int方法

2024-06-01 09:28:12 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个代码,但我不确定它是如何工作的:

    def getValue(number):
        return int(number,16)

所以如果我在这个数字中加上'a25',它应该返回2597,但是我的问题是这个int函数是如何工作的,有没有其他方法可以做到这一点?在


Tags: 方法函数代码numberreturndef数字int
2条回答

假设number以16为基数,那么这个函数返回与该数字等价的int。在

看这个definition of int method

它的工作原理如下:

import string
allChars = string.digits+string.lowercase #get a list of all the 'characters' which represent digits
def toInt(srep,base):
    charMap = dict(zip(allChars,range(len(allChars)))) #map each 'character' to the base10 number
    num = 0 #the current total
    index = len(srep)-1 #the current exponent
    for digit in srep:
        num += charMap[digit]*base**index
        index -= 1
    return num 

解释“a16”的一些调试打印的过程是:

^{pr2}$

相关问题 更多 >