How do I check if a string is a negative number before passing it through int()?
Asked Answered
R

7

7

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 recognize it as a number when "-" is included.

This is what I have so far:

def contestTest():
    # Neutral point for struggle/tug of war/contest
    x = 0
    
    while -5 < x < 5:
        print "Type desired amount of damage."
        print x
        choice = raw_input("> ")
        
        if choice.isdigit():
            y = int(choice)
            x += y
        else:
            print "Invalid input."
    
    if -5 >= x:
        print "x is low. Loss."
        print x
    elif 5 <= x:
        print "x is high. Win."
        print x
    else:
        print "Something went wrong."
        print x

The only solution I can think of is some separate, convoluted series of statements that I might squirrel away in a separate function to make it look nicer.

Regression answered 26/5, 2016 at 22:59 Comment(1)
what is wrong with: kite.com/python/answers/….Standby
Y
15

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
while True:
    choice = raw_input("> ")
    try:
        y = int(choice)
        break
    except ValueError:
        print "Invalid input."
x += y
Yalonda answered 26/5, 2016 at 23:0 Comment(1)
maybe it is better: choice.lstrip('-+').isnumeric()Marrowfat
A
3

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."
Adapt answered 26/5, 2016 at 23:10 Comment(0)
R
1

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():
   #operation
else:
   #operation

you can try

try:
    x = float(raw_input)
except ValueError:
    print ("What you entered is not a number")

I haven't tested if replacing float with int works.

I saw this on Python's documentation as well (2.7.11) here.

Rentsch answered 26/5, 2016 at 23:13 Comment(0)
S
0

This may be simpler:

def is_negative_int(value: str) -> bool:
    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

References:

Standby answered 26/11, 2021 at 18:40 Comment(0)
O
0

If you just want integers and reject decimal numbers, you can use the following function to check.

def isInteger(string):
  if string[0] == '-': #if a negative number
    return string[1:].isdigit()
  else:
    return string.isdigit()
Oona answered 18/6, 2023 at 1:18 Comment(0)
T
0

You may use a regular expressions to check if the string has the pattern of an integer number before attempting any casting:

import re
patternInteger = re.compile("^[+-]?[0-9]+$")

if patternInteger.match(string):
    return int(string)
else:
    return "This string is not an integer number"

You can generalize your regex pattern to match other kind of strings that may look like floating point numbers or even complex numbers. In this situation regex might be a bit overkill but can be very useful to learn if in the future you have to deal with a more general pattern to recognise.

Tropo answered 18/6, 2023 at 1:38 Comment(0)
N
-1
a = "-1"

def is_number(string:str):
    if string.isdigit():
        return f'число = {string.isdigit()}'

    elif string[0] == '-':
        if string[1:].isdigit():
            return f'отрицательное число = {int(string[1:]) * -1}'

    else:
        return f'Ввели не число'

print(f"Итоги: {is_number(a)}")
Naylor answered 25/8 at 20:22 Comment(1)
Please translate all text to EnglishGilolo

© 2022 - 2024 — McMap. All rights reserved.