如何从用户输入的float中删除一组字符 - Python

时间:2018-06-14 04:47:44

标签: 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米”,“1.8米”或“1.8毫秒”以及相当于千克的程序,该程序将删除额外的输入并处理它,就好像他们没有补充说。此外,您对我的任何额外提示都会很棒。谢谢!

2 个答案:

答案 0 :(得分:1)

用这个替换第三行:

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

它的工作原理是在转换为float之前删除所有字母。

答案 1 :(得分:1)

一般来说,这是有效的

Height_List = []
Height  = input("What is your height")
for i  in Height:
    if i in "1234567890.":
        Height_List.append(i)
Actual_Height = float("".join(Height_List))