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

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

提交回复
热议问题