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

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

    >>> "+7".lstrip("-+").isdigit()
    True
    >>> "-7".lstrip("-+").isdigit()
    True
    >>> "7".lstrip("-+").isdigit()
    True
    >>> "13.4".lstrip("-+").isdigit()
    False
    

    So your function would be:

    def is_int(val):
       return val.lstrip("-+").isdigit()
    

提交回复
热议问题