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

前端 未结 19 1851
悲哀的现实
悲哀的现实 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:59

    with positive integers you could use .isdigit:

    >>> '16'.isdigit()
    True
    

    it doesn't work with negative integers though. suppose you could try the following:

    >>> s = '-17'
    >>> s.startswith('-') and s[1:].isdigit()
    True
    

    it won't work with '16.0' format, which is similar to int casting in this sense.

    edit:

    def check_int(s):
        if s[0] in ('-', '+'):
            return s[1:].isdigit()
        return s.isdigit()
    
    0 讨论(0)
  • 2020-11-22 00:59

    I suggest the following:

    import ast
    
    def is_int(s):
        return isinstance(ast.literal_eval(s), int)
    

    From the docs:

    Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

    I should note that this will raise a ValueError exception when called against anything that does not constitute a Python literal. Since the question asked for a solution without try/except, I have a Kobayashi-Maru type solution for that:

    from ast import literal_eval
    from contextlib import suppress
    
    def is_int(s):
        with suppress(ValueError):
            return isinstance(literal_eval(s), int)
        return False
    

    ¯\_(ツ)_/¯

    0 讨论(0)
  • 2020-11-22 01:01

    str.isdigit() should do the trick.

    Examples:

    str.isdigit("23") ## True
    str.isdigit("abc") ## False
    str.isdigit("23.4") ## False
    

    EDIT: As @BuzzMoschetti pointed out, this way will fail for minus number (e.g, "-23"). In case your input_num can be less than 0, use re.sub(regex_search,regex_replace,contents) before applying str.isdigit(). For example:

    import re
    input_num = "-23"
    input_num = re.sub("^-", "", input_num) ## "^" indicates to remove the first "-" only
    str.isdigit(input_num) ## True
    
    0 讨论(0)
  • 2020-11-22 01:01

    Uh.. Try this:

    def int_check(a):
        if int(a) == a:
            return True
        else:
            return False
    

    This works if you don't put a string that's not a number.

    And also (I forgot to put the number check part. ), there is a function checking if the string is a number or not. It is str.isdigit(). Here's an example:

    a = 2
    a.isdigit()
    

    If you call a.isdigit(), it will return True.

    0 讨论(0)
  • 2020-11-22 01:04
    def is_int_or_float(x):
        try:    
            if int(float(x)):
                if float(x).is_integer():  return 'int'
                else:                      return 'float'
        except ValueError:  return False
    
    
    for  i  in ['*', '-1', '01', '1.23', '+0011.002', ]:
        print(i, is_int_or_float(i))
    
    # * False
    # -1 int
    # 01 int
    # 1.23 float
    # +0011.002 float
    
    0 讨论(0)
  • 2020-11-22 01:06

    If you're really just annoyed at using try/excepts all over the place, please just write a helper function:

    def RepresentsInt(s):
        try: 
            int(s)
            return True
        except ValueError:
            return False
    
    >>> print RepresentsInt("+123")
    True
    >>> print RepresentsInt("10.0")
    False
    

    It's going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one.

    0 讨论(0)
提交回复
热议问题