python里 try里怎么用int函数_在Python中使用try/except将字符串转换为Int

首先,^{} / ^{}不是函数,而是语句。

要在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'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值