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

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

    Use a regular expression:

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

    If you must accept decimal fractions also:

    def RepresentsInt(s):
        return re.match(r"[-+]?\d+(\.0*)?$", s) is not None
    

    For improved performance if you're doing this often, compile the regular expression only once using re.compile().

提交回复
热议问题