Search code examples
pythonif-statementinputreplaceisnumeric

Why replace in this code approves float numbers as numeric . I have tried floats without replace and I am getting message that it is not a number


#user inputs a number
number = input("Enter number: ")
# 1) changes dot and creates a new string,2) verifies is it a number
if(not number.replace(".","").isnumeric()):
    print("Sorry number is not numeric")

Generally replace changes old value with a new one.


Solution

  • isnumeric returns True if and only if every character of the string is a numeric character as defined by Unicode. Periods are not numeric, but many characters that contain or represent numbers, such as ½ or , are considered numeric.

    First, you probably want isdigit instead, because a lot of the numeric characters in Unicode aren't valid in float numbers. isdigit only returns True if every character is one of the ASCII digits 0-9.

    Second, to validate if the input is a float, it's "Better to Ask Forgiveness than Permission": try converting it as a float directly, and see if that fails:

    try:
        float(number)
    except ValueError:
        print("Sorry number is not a float")