Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for negative numbers at the beginning of a string?

Tags:

python

I am trying to add a piece of code to this string to check for a negative number in the first position. If the code identifies a negative number it should return "False". I'm having trouble with int and str at the user input command.

def is_number(S):
    #if s < 0:
        #print("False")
    #else:   
        try:
            float(s)
            return True
        except ValueError:
            pass
 
        try:
            import unicodedata
            unicodedata.numeric(s)
            return True
        except (TypeError, ValueError):
            pass
        return False
  
s = input()

is_number(s)

The above code should accept numeric and alpha inputs without throwing an error.

like image 232
Lemon8ter Avatar asked Aug 31 '25 17:08

Lemon8ter


2 Answers

Is this what you want?

def check_negative(s):
    try:
        f = float(s)
        if (f < 0):
            return True
        # Otherwise return false
        return False
    except ValueError:
        return False

Not entirely sure if this is what you want though, maybe you should see ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000's answer

like image 136
heo Avatar answered Sep 02 '25 07:09

heo


You can replace your is_number function with this code:

def is_number(s):
    return str(s)[0] == '-' and len(str(s)) > 1

It is a function which checks whether the first character is a negative sign, and if it is, it will return true. Otherwise, the number cannot be negative, and it will then return false. However, if there is only a - sign, then it is neither and will return false. It only uses one line and is much simpler. It works for strings and floats too.

like image 29
whackamadoodle3000 Avatar answered Sep 02 '25 05:09

whackamadoodle3000