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

前端 未结 19 2131
悲哀的现实
悲哀的现实 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 00:55

    Here is a function that parses without raising errors. It handles obvious cases returns None on failure (handles up to 2000 '-/+' signs by default on CPython!):

    #!/usr/bin/env python
    
    def get_int(number):
        splits = number.split('.')
        if len(splits) > 2:
            # too many splits
            return None
        if len(splits) == 2 and splits[1]:
            # handle decimal part recursively :-)
            if get_int(splits[1]) != 0:
                return None
    
        int_part = splits[0].lstrip("+")
        if int_part.startswith('-'):
            # handle minus sign recursively :-)
            return get_int(int_part[1:]) * -1
        # successful 'and' returns last truth-y value (cast is always valid)
        return int_part.isdigit() and int(int_part)
    

    Some tests:

    tests = ["0", "0.0", "0.1", "1", "1.1", "1.0", "-1", "-1.1", "-1.0", "-0", "--0", "---3", '.3', '--3.', "+13", "+-1.00", "--+123", "-0.000"]
    
    for t in tests:
        print "get_int(%s) = %s" % (t, get_int(str(t)))
    

    Results:

    get_int(0) = 0
    get_int(0.0) = 0
    get_int(0.1) = None
    get_int(1) = 1
    get_int(1.1) = None
    get_int(1.0) = 1
    get_int(-1) = -1
    get_int(-1.1) = None
    get_int(-1.0) = -1
    get_int(-0) = 0
    get_int(--0) = 0
    get_int(---3) = -3
    get_int(.3) = None
    get_int(--3.) = 3
    get_int(+13) = 13
    get_int(+-1.00) = -1
    get_int(--+123) = 123
    get_int(-0.000) = 0
    

    For your needs you can use:

    def int_predicate(number):
         return get_int(number) is not None
    

提交回复
热议问题