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

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

    If you want to accept lower-ascii digits only, here are tests to do so:

    Python 3.7+: (u.isdecimal() and u.isascii())

    Python <= 3.6: (u.isdecimal() and u == str(int(u)))

    Other answers suggest using .isdigit() or .isdecimal() but these both include some upper-unicode characters such as '٢' (u'\u0662'):

    u = u'\u0662'     # '٢'
    u.isdigit()       # True
    u.isdecimal()     # True
    u.isascii()       # False (Python 3.7+ only)
    u == str(int(u))  # False
    

提交回复
热议问题