Python 如何知道列表中的字符串何时不能转换为整数?
这样,如果存在无法转换为整数的字符串,则会生成错误消息 例如:Python 如何知道列表中的字符串何时不能转换为整数?,python,string,list,Python,String,List,这样,如果存在无法转换为整数的字符串,则会生成错误消息 例如: List = ['1', '2', 'a', '4/2'] ->produce error message List2 = ['1', '2', '4/2'] ->proceed to condition 有一个字符串函数叫做isdigit print '4'.isdigit() True 如果解析列表时只需要一条错误消息,则可以尝试: try: [eval(x) for x in list] #
List = ['1', '2', 'a', '4/2']
->produce error message
List2 = ['1', '2', '4/2']
->proceed to condition
有一个字符串函数叫做isdigit
print '4'.isdigit()
True
如果解析列表时只需要一条错误消息,则可以尝试:
try:
[eval(x) for x in list]
# Do whatever with list here
except:
#Error code here
如果您担心这一点,这并不是最好的方法,也可能不是最安全的方法,但可能有助于实现您想要的功能。您知道什么时候无法转换为整数,因为它会抛出一个错误
for x in mylist:
try:
int(x)
except:
print("not possible to convert into int_variable")
请注意,使用此代码块,只有“1”和“2”被转换为整数“显然是一个角色。”4/2'是由数字组成的字符串。它不是作为数学表达式计算的。这样做需要更复杂的逻辑
try/except逻辑很简单-将项转换为整数。如果抛出ValueException失败,则不能成为整数
最后,有几个其他答案是try/except块。但是,它们没有捕获特定的异常类型。这是错误的捕获特定异常 4/2不能转换为整数,至少不能通过int4/2转换。。您打算如何转换这些字符串?如果您足够努力,任何东西都可以转换为整数。@nu993t-您也有大整数,这会使本机数据类型溢出。@jww:Python处理大整数时不会出现问题。请对您的回答作些解释,至少使用并捕获特定的异常。而且,这根本不能确保生成整数。可以是任何对象。“-4”。isdigit为False。
>>> list1 = ['1', '2', 'a', '4/2']
>>> for x in list1:
... try:
... int(x)
... except ValueError:
... print "Can't convert '%s' to an int" % x
...
1
2
Can't convert 'a' to an int
Can't convert '4/2' to an int