首页 > 解决方案 > 如何从用户输入的浮点数中删除一组字符 - Python

问题描述

我刚开始学习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 米”或“1.8 ms”以及千克等值,程序将删除额外的输入并处理它,就好像他们没有添加那个。此外,您对我的任何额外提示都会很棒。谢谢!

标签: python

解决方案


将第三行替换为:

height_m = float(''.join([e for e in input("Enter your height in meters: ") if not e.isalpha()]))

它通过在转换为浮点数之前删除所有字母来工作。


推荐阅读