How can I check if a string represents an int, without using try/except?

前端 未结 19 1848
悲哀的现实
悲哀的现实 2020-11-22 00:36

Is there any way to tell whether a string represents an integer (e.g., \'3\', \'-17\' but not \'3.14\' or \'asf

19条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 01:12

    I really liked Shavais' post, but I added one more test case ( & the built in isdigit() function):

    def isInt_loop(v):
        v = str(v).strip()
        # swapping '0123456789' for '9876543210' makes nominal difference (might have because '1' is toward the beginning of the string)
        numbers = '0123456789'
        for i in v:
            if i not in numbers:
                return False
        return True
    
    def isInt_Digit(v):
        v = str(v).strip()
        return v.isdigit()
    

    and it significantly consistently beats the times of the rest:

    timings..
    isInt_try:   0.4628
    isInt_str:   0.3556
    isInt_re:    0.4889
    isInt_re2:   0.2726
    isInt_loop:   0.1842
    isInt_Digit:   0.1577
    

    using normal 2.7 python:

    $ python --version
    Python 2.7.10
    

    Both the two test cases I added (isInt_loop and isInt_digit) pass the exact same test cases (they both only accept unsigned integers), but I thought that people could be more clever with modifying the string implementation (isInt_loop) opposed to the built in isdigit() function, so I included it, even though there's a slight difference in execution time. (and both methods beat everything else by a lot, but don't handle the extra stuff: "./+/-" )

    Also, I did find it interesting to note that the regex (isInt_re2 method) beat the string comparison in the same test that was performed by Shavais in 2012 (currently 2018). Maybe the regex libraries have been improved?

提交回复
热议问题