首先,^{} / ^{}不是函数,而是语句。
要在Python中将字符串(or any other type that can be converted)转换为整数,只需调用^{}内置函数。int()将raisea^{}如果失败,您应该特别注意:
在Python 2中。x:>>> for value in '12345', 67890, 3.14, 42L, 0b010101, 0xFE, 'Not convertible':
... try:
... print '%s as an int is %d' % (str(value), int(value))
... except ValueError as ex:
... print '"%s" cannot be converted to an int: %s' % (value, ex)
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'
在Python 3中。x
语法略有变化:>>> for value in '12345', 67890, 3.14, 42, 0b010101, 0xFE, 'Not convertible':
... try:
... print('%s as an int is %d' % (str(value), int(value)))
... except ValueError as ex:
... print('"%s" cannot be converted to an int: %s' % (value, ex))
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'