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

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

提交回复
热议问题