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

前端 未结 19 2165
悲哀的现实
悲哀的现实 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条回答
  •  Happy的楠姐
    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.

提交回复
热议问题