I get the following result:
>>> x = '-15'
>>> print x.isdigit()
False
When I expect it to be True
. There seems to be no built in function that returns True
for a string of negative number. What is the recommend to detect it?
I get the following result:
>>> x = '-15'
>>> print x.isdigit()
False
When I expect it to be True
. There seems to be no built in function that returns True
for a string of negative number. What is the recommend to detect it?
The recommended way would be to try
it:
try:
x = int(x)
except ValueError:
print "{} is not an integer".format(x)
If you also expect decimal numbers, use float()
instead of int()
.
There might be a more elegant Python way, but a general method is to check if the first character is '-'
, and if so, call isdigit
on the 2nd character onward.
Maybe regex is an overhead here, but this could catch +
and -
before a number, and also could catch float
and int
as well:
(based on @Mark's comment)
CODE:
import re
def isdigit(string):
return bool(re.match(r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)', string))
DEMO:
print isdigit('12') # True
print isdigit('-12') # True
print isdigit('aa') # False
print isdigit('1a2a') # False
print isdigit('-12-12') # False
print isdigit('-12.001') # True
print isdigit('+12.001') # True
print isdigit('.001') # True
print isdigit('+.001') # True
print isdigit('-.001') # True
print isdigit('-.') # False
Use lstrip
:
>>> negative_number = "-1"
>>> negative_number.lstrip('-').isnumeric()
True
>>> positive_number = "2"
>>> positive_number.lstrip('-').isnumeric()
True