You can not check negative numbers with the isnumeric function in Python. Python isnumeric()
is used to check whether a given string consists of only numeric characters or not. However, this method does not consider negative numbers as numeric characters.
Python isnumeric negative numbers example
Simple example code isnumeric()
method returns True
for the string "123"
, but it returns False
for the string "-123"
.
a = "123"
print(a, a.isnumeric())
b = "-123"
print(b, b.isnumeric())
Output:
Alternatively, you can use a regular expression to check whether a given string represents a negative number or not.
import re def is_number(s): return bool(re.match(r'^-?\d+(?:\.\d+)?$', s)) print(is_number('123')) # True print(is_number('-123')) # True print(is_number('A1')) #False
One simple way to check if a string is a number or not is to try to convert it to a number using a built-in Python function like int()
or float()
. If the conversion succeeds, then the string is a number; otherwise, an exception will be raised.
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
Note: the isdigit() method does not consider negative numbers as numeric characters.
Do comment if you have any doubts or suggestions on this Python isnumeric function topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.