使用下面提供的示例将字符串百分比转换为浮点数的简洁方法是什么?

时间:2016-12-01 02:33:00

标签: python string python-3.x floating-point

我正在寻找一个更加愚蠢的'我有这个问题的解决方案的版本。以下是我的代码。

我试图同时允许%符号和一个数字作为user.anyone的百分比输入,这可以帮助我写出来比previous examples解释更多请。

PUBLIC NAME COLUMN

1 个答案:

答案 0 :(得分:2)

您链接的问题有答案描述使用str.strip(尽管rstrip更合适)删除尾随%(如果存在)。只需在input返回后将其传递给float,然后将该行更改为:

percent = float(input('Enter percentage: ').rstrip('%'))

如果您希望将其拆分以保持清晰:

maybe_percent_sign_str = input('Enter percentage: ')
no_percent_sign_str = maybe_percent_sign_str.rstrip('%')
percent = float(no_percent_sign_str)