将字符串转换为使用try/除去Python。

[英]Converting String to Int using try/except in Python


So I'm pretty stumped on how to convert a string into an int using the try/except function. Does anyone know a simple function on how to do this? I feel like I'm still a little hazy on string and ints. I'm pretty confident that ints are related to numbers. Strings...not so much.

所以我很难为如何使用try/except函数将字符串转换为int。有人知道怎么做这个简单的函数吗?我觉得我还是有点模糊。我很有信心,ints与数字有关。弦……并非如此。

3 个解决方案

#1


37  

It is important to be specific about what exception you're trying to catch when using a try/except block.

在使用try/除去块时,您需要了解什么异常是非常重要的。

string = "abcd"
try:
    i = int(string)
    print i
except ValueError:
    #Handle the exception
    print 'Please enter an integer'

Try/Excepts are powerful because if something can fail in a number of different ways, you can specify how you want the program to react in each fail case.

尝试/例外是很强大的,因为如果某些事情可以以不同的方式失败,那么您可以指定您希望该程序在每个失败案例中的反应。

#2


10  

Here it is:

这里是:

s = "123"
try:
  i = int(s)
except ValueError as verr:
  pass # do job to handle: s does not contain anything convertible to int
except Exception as ex:
  pass # do job to handle: Exception occurred while converting to int

#3


6  

Firstly, try / except are not functions, but statements.

首先,尝试/除了不是函数,而是语句。

To convert a string (or any other type that can be converted) to an integer in Python, simply call the int() built-in function. int() will raise a ValueError if it fails and you should catch this specifically:

要将字符串(或可转换的任何其他类型)转换为Python中的整数,只需调用int()内置函数。int()如果失败,将会引发一个ValueError错误,您应该特别注意:

In 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'

In Python 3.x

the syntax has changed slightly:

语法略有变化:

>>> 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'
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2011/11/10/cfb13a43ac50cad5cc43bcea62b1847a.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告