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

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

    Greg Hewgill's approach was missing a few components: the leading "^" to only match the start of the string, and compiling the re beforehand. But this approach will allow you to avoid a try: exept:

    import re
    INT_RE = re.compile(r"^[-]?\d+$")
    def RepresentsInt(s):
        return INT_RE.match(str(s)) is not None
    

    I would be interested why you are trying to avoid try: except?

提交回复
热议问题