How Do I Check If A String Is A Negative Number Before Passing It Through Int()?
I'm trying to write something that checks if a string is a number or a negative. If it's a number (positive or negative) it will passed through int(). Unfortunately isdigit() won't
Solution 1:
You can easily remove the characters from the left first, like so:
choice.lstrip('-+').isdigit()
However it would probably be better to handle exceptions from invalid input instead:
print x
whileTrue:
choice = raw_input("> ")
try:
y = int(choice)
breakexcept ValueError:
print"Invalid input."
x += y
Solution 2:
Instead of checking if you can convert the input to a number you can just try the conversion and do something else if it fails:
choice = raw_input("> ")
try:
y = int(choice)
x += y
except ValueError:
print"Invalid input."
Solution 3:
You can solve this by using float(str)
. float should return an ValueError if it's not a number. If you're only dealing with integers you can use int(str)
So instead of doing
if choise.isdigit():
#operationelse:
#operation
You can try
try:
x = float(raw_input)
except ValueError:
print ("What you entered is not a number")
Feel free to replace float
with int
, and tell me if it works! I haven't tested it myself.
EDIT: I just saw this on Python's documentation as well (2.7.11) here
Solution 4:
isn't this simpler?
def is_negative_int(value: str) -> bool:
"""
ref:
- https://www.kite.com/python/answers/how-to-check-if-a-string-represents-an-integer-in-python#:~:text=To%20check%20for%20positive%20integers,rest%20must%20represent%20an%20integer.
- https://stackoverflow.com/questions/37472361/how-do-i-check-if-a-string-is-a-negative-number-before-passing-it-through-int
"""if value == "":
return False
is_positive_integer: bool = value.isdigit()
if is_positive_integer:
return True
else:
is_negative_integer: bool = value.startswith("-") and value[1:].isdigit()
is_integer: bool = is_positive_integer or is_negative_integer
return is_integer
Post a Comment for "How Do I Check If A String Is A Negative Number Before Passing It Through Int()?"