int()函数与2个args在Python中做什么

时间:2014-12-30 22:08:16

标签: python int

在下面的代码中,int()对这两个参数做了什么:

if (i=='0X0F'):
    stat = int(log[i+1],16)

2 个答案:

答案 0 :(得分:11)

class int(object)
 |  int(x=0) -> int or long
 |  int(x, base=10) -> int or long
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is floating point, the conversion truncates towards zero.
 |  If x is outside the integer range, the function returns a long instead.
 |  
 |  If x is not a number or if base is given, then x must be a string or
 |  Unicode object representing an integer literal in the given base.  The
 |  literal can be preceded by '+' or '-' and be surrounded by whitespace.
 |  The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
 |  interpret the base from the string as an integer literal.

答案 1 :(得分:3)

第二个参数告诉int输入字符串的基础。来自帮助:

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |  
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.

因此,如果您执行int(S, B),则会转换S,这是基数B中数字的字符串表示形式:

In [63]: int('10', 2)
Out[63]: 2

In [64]: int('10', 3)
Out[64]: 3

现在,如果B大于10,则python假定下一个数字序列来自ABCD...。因此:

In [65]: int("A", 11)
Out[65]: 10