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

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

    This is probably the most straightforward and pythonic way to approach it in my opinion. I didn't see this solution and it's basically the same as the regex one, but without the regex.

    def is_int(test):
        import string
        return not (set(test) - set(string.digits))
    

提交回复
热议问题