Python 函数 int(x, base=10)
由下面文档给出的可以看出 int([x]) 与 int(x, base=10) 都是 int.__init__ 的一种special case
def __init__(self, x, base=10): # known special case of int.__init__ """ int([x]) -> 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('0b100', base=0) 4 # (copied from class doc) """ pass
12345678910111213141516171819' 有两个重要的部分如果x不是数字,或者如果给定了基数,那么x必须是表示整数文本的字符串、字节或字节组实例
基本值默认为10。有效基数为0和2-36。基数0表示将字符串中的基解释为整型文本。
x 默认 base = 10base = 0 表示根据自行给出的 x(系统自己识别)得出十进制的结果x 必须是字符串、字节或字节组int(x, base) -> integer 无论 base 等于几,得出来的都是十进制的整数,也就是base 中的几进制是限制 x 的,通过此运算得出对应的十进制例如上面的例子:
>>> int('0b100', base=0) 4 12
0b 代表二进制的意思,base = 0,由于有 0b 系统自己可以识别出是二进制,故输出的是 4
若没有 0b 哪
>>> int('100', base=0) 4 123
这样就一目了然了