Is there any way to tell whether a string represents an integer (e.g., \'3\'
, \'-17\'
but not \'3.14\'
or \'asf
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