Python's isdigit() method returns False for negative numbers

*爱你&永不变心* 提交于 2020-07-16 10:44:08

问题


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" ...]

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])

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?


回答1:


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.




回答2:


The way to convert to integers is to try the conversion and be prepared for it to fail:

for i in range(len(mylist)):
    try:
        mylist[i] = int(mylist[i])
    except ValueError:
        pass



回答3:


Try it, and catch the exception if it fails:

try:
    return int(obj)
except ValueError:
    ...

Python takes the view of it's easier to ask for forgiveness than permission. Looking before you leap is often slower, harder to read, and can often introduce race conditions (not in this instance, but in general).

Also, modifying a list in-place like that is a bad idea, as accessing by index in Python is slow. Instead, consider using a list comprehension like this:

def intify(obj):
    try:
        return int(obj)
    except ValueError:
        return obj

mylist_with_ints = [intify(obj) for obj in mylist]

This makes a new list with the modified values and is more readable and efficient.

As a note, as we are just applying a function to every item of a list, map() would also work well here:

mylist_with_ints = map(intify, mylist)

Note that if you need a list instead of an iterable in 3.x, you will want to wrap the map call in list().



来源:https://stackoverflow.com/questions/15720176/pythons-isdigit-method-returns-false-for-negative-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!