Python的isdigit()方法为负数返回False [英] Python's isdigit() method returns False for negative numbers

查看:507
本文介绍了Python的isdigit()方法为负数返回False的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个阅读到列表的文本文件.此列表包含整数和字符串.

I have a text files that I read to a list. This list contains integers and strings.

例如,我的列表可能如下所示:

For example, my list could look like this:

["name", "test", "1", "3", "-3", "name" ...]

现在,我想使用.isdigit()方法或isinstance()函数将所有数字转换为整数. 例如:

Now, I want to convert all numbers into integers using the .isdigit() method or the isinstance() function. for example:

for i in range len(mylist):
    if mylist[i].isdigit():
        mylist[i] =  int(mylist[i])

问题是例如"-3".isdigit()会返回False.有什么技巧可以解决该问题并将负数字字符串转换为负整数?

The problem is that "-3".isdigit() for example would return False. Any tips for a simple solution to circumvent the problem and convert negative-digit-strings into negative integers?

推荐答案

该方法仅测试位数,而-不是数字.如果要检测整数,则需要使用int()进行测试并捕获ValueError异常:

The method tests for digits only, and - is not a digit. You need to test with int() and catch the ValueError exception instead if you wanted to detect integers:

for i, value in enumerate(mylist):
    try:
        mylist[i] = int(value)
    except ValueError:
        pass  # not an integer

换句话说,不需要进行显式测试;只是转换并捕获异常.寻求宽恕而不是寻求许可.

In other words, there is no need to test explicitly; just convert and catch the exception. Ask forgiveness rather than ask for permission.

这篇关于Python的isdigit()方法为负数返回False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆