为什么在此代码中替换将浮点数批准为数字。我试过没有替换的浮点数,但我收到消息说它不是数字

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.

isnumeric returns 当且仅当字符串的每个 字符 都是数字字符 as defined by Unicode 时为真。句点不是数字,但许多包含或代表数字的字符,例如 ½,被视为数字。

首先,您可能需要 isdigit,因为 Unicode 中的许多数字字符在浮点数中无效。 isdigit 仅 returns 如果每个字符都是 ASCII 数字 0-9 之一则为真。

其次,要验证输入是否为浮点数,“请求宽恕比请求许可更好”:尝试将其直接转换为浮点数,看看是否失败:

try:
    float(number)
except ValueError:
    print("Sorry number is not a float")
number = input("Enter number: ")
if(not number.replace(".","").isnumeric()):
    print("Sorry number is not numeric")

Replace here change dot, creates a new string and makes isnumeric() to be True for float numbers.