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