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

后端 未结 3 1736
长情又很酷
长情又很酷 2021-01-29 12:35

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条回答
  •  一生所求
    2021-01-29 13:37

    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.

提交回复
热议问题