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

标签 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 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/

相关文章:

python - raw_input 占位符?

python - 压缩文件路径中的所有文件

python - IPython,每次关闭终端前都会提示

Python 错误 - 无法重定向设置的 url

python - 如何基于相同的日期时间 x 轴同时绘制两个不同的数据框列

python - 什么时候(以及为什么)引入 Python `__new__()`?

python - django 中的 URL 模式匹配

python - Django 2.0 身份验证 View 中 Reset Done 和 reset Complete 的区别

python - 使用 Keras 使用 ANN 预测正弦

python - 为什么我不能从多处理队列中捕获 Queue.Empty 异常?