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

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

    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
    

    ¯\_(ツ)_/¯

提交回复
热议问题