Is there any way to tell whether a string represents an integer (e.g., \'3\'
, \'-17\'
but not \'3.14\'
or \'asf
I suggest the following:
import ast
def is_int(s):
return isinstance(ast.literal_eval(s), int)
From the docs:
Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
I should note that this will raise a ValueError
exception when called against anything that does not constitute a Python literal. Since the question asked for a solution without try/except, I have a Kobayashi-Maru type solution for that:
from ast import literal_eval
from contextlib import suppress
def is_int(s):
with suppress(ValueError):
return isinstance(literal_eval(s), int)
return False
¯\_(ツ)_/¯