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 米”或“1.8 ms”以及千克等值,程序将删除额外的输入并处理它,就好像他们没有添加那个。此外,您对我的任何额外提示都会很棒。谢谢!
解决方案
将第三行替换为:
height_m = float(''.join([e for e in input("Enter your height in meters: ") if not e.isalpha()]))
它通过在转换为浮点数之前删除所有字母来工作。
推荐阅读
- c# - 如何在 .NET 5 MVC 项目的浏览器中存储 JWT 令牌
- selenium-webdriver - 如何编写 XPATH 以获取以下元素文本?
- python - Pywinusb:如何使用 HID 键盘解释原始输入示例的结果?
- c - 条件运算符的结果是左值还是右值?
- python - ArgumentError:映射器映射类用户->用户无法为映射表“用户”组装任何主键列
- c++ - 有什么方法可以在循环中获取用户输入而不暂停循环以请求它?
- c - C 生成文件命令
- html - Setting a time for how long it will take for a transition to finish
- flutter - Flutter - 使用 pushNamedAndRemoveUntil 时按下系统后退按钮关闭应用程序
- javascript - 等待后什么都不执行