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
a = "123"
b = "-123"
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
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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.