我刚开始接触python,我想知道如何做我在标题中所说的。我唯一的编程背景是我在高中时上的一个学期的 C++ 课,我得到了 C,几乎忘记了所有的东西。这是我的代码:
while True:
try:
height_m = float(input("Enter your height in meters: "))
except ValueError:
print ("Please enter a number without any other characters.")
continue
else:break
while True:
try:
weight_kg = float(input("Enter your weight in kilograms: "))
except ValueError:
print ("Please enter a number without any other characters.")
continue
else:break
bmi = weight_kg / (height_m ** 2)
print ("Your bmi is",(bmi),".")
if bmi < 18.5:
print ("You are underweight.")
elif 18.5 <= bmi <=24.9:
print ("You are of normal weight.")
elif 25 <= bmi <= 29.9:
print ("You are overweight.")
else:
print ("You are obese.")
如您所见,它只是一个基本的 BMI 计算器。然而,我想做的是,如果有人输入“1.8 m”、“1.8 meters”或“1.8 ms”以及公斤的等效值,程序将删除额外的输入并像他们一样处理它没有添加那个。另外,如果你有任何额外的建议,我会非常高兴。谢谢!
最佳答案
将第三行替换为:
height_m = float(''.join([e for e in input("Enter your height in meters: ") if not e.isalpha()]))
它的工作原理是在转换为 float 之前删除所有字母。
关于python - 如何从用户输入的 float 中删除一组字符 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50849790/