Looks like there's so far only two answers that handle negatives and decimals (the try... except answer and the regex one?). Found a third answer somewhere a while back somewhere (tried searching for it, but no success) that uses explicit direct checking of each character rather than a full regex.
Looks like it is still quite a lot slower than the try/exceptions method, but if you don't want to mess with those, some use cases may be better compared to regex when doing heavy usage, particularly if some numbers are short/non-negative:
>>> from timeit import timeit
On Python 3.10 on Windows shows representative results for me:
Explicitly check each character:
>>> print(timeit('text="1234"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])')) 0.5673831000458449 >>> print(timeit('text="-4089175.25"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])')) 1.0832774000009522 >>> print(timeit('text="-97271851234.28975232364"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])')) 1.9836419000057504
A lot slower than the try/except:
>>> def exception_try(string): ... try: ... return type(float(string)) == int ... except: ... return false >>> print(timeit('text="1234"; exception_try(text)', "from __main__ import exception_try")) 0.22721579996868968 >>> print(timeit('text="-4089175.25"; exception_try(text)', "from __main__ import exception_try")) 0.2409859000472352 >>> print(timeit('text="-97271851234.28975232364"; exception_try(text)', "from __main__ import exception_try")) 0.45190039998851717
But a fair bit quicker than regex, unless you have an extremely long string?
>>> print(timeit('import re')) 0.08660140004940331
(In case you're using it already)... and then:
>>> print(timeit('text="1234"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)')) 1.3882658999646083 >>> print(timeit('text="-4089175.25"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)')) 1.4007637000177056 >>> print(timeit('text="-97271851234.28975232364"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)')) 1.4191589000402018
None are close to the simplest isdecimal, but that of course won't catch the negatives...
>>> print(timeit('text="1234"; text.isdecimal()')) 0.04747540003154427
Always good to have options depending on needs?
if type(eval(user_input)) == int:this might work.