Python 使用下面提供的示例,将字符串百分比转换为浮点的干净方法是什么?
我正在寻找一个更“简化”的版本来解决这个问题。下面是我的代码 我正在尝试将%符号和简单的数字作为用户百分比的输入。任何能帮助我的人都必须为我写出这篇文章,而不仅仅是解释Python 使用下面提供的示例,将字符串百分比转换为浮点的干净方法是什么?,python,string,python-3.x,floating-point,Python,String,Python 3.x,Floating Point,我正在寻找一个更“简化”的版本来解决这个问题。下面是我的代码 我正在尝试将%符号和简单的数字作为用户百分比的输入。任何能帮助我的人都必须为我写出这篇文章,而不仅仅是解释 #104 Percentages print('#104 Percentages') percent = float(input('Enter percentage: ')) decimal = percent/100 print('Equivalent decimal:',round(decimal,2)) print()
#104 Percentages
print('#104 Percentages')
percent = float(input('Enter percentage: '))
decimal = percent/100
print('Equivalent decimal:',round(decimal,2))
print()
您链接的问题的答案描述了如何使用
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)
您链接的问题的答案描述了如何使用
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)
您可以
输入(…).strip('%')
以允许或不允许%
。只需格式化输出,而不是round()
,例如print('equired decimal:{.2f}'。format(decimal))
。但是这不是已经在你链接的帖子中得到了回答吗?可能是重复的谢谢!我感谢你的反馈。ShadowRanger(如下所示)很好地解决了我可以使用verbatm的代码问题。您可以输入(…).strip('%')
来允许%
或不允许。只需格式化输出,而不是round()
,例如print('equired decimal:{.2f}'。format(decimal))
。但是这不是已经在你链接的帖子中得到了回答吗?可能是重复的谢谢!我感谢你的反馈。暗影游侠(如下所示)用我可以使用的代码很好地解决了我的问题。非常感谢你的暗影游侠!你解决了我的问题。我很感激你回答这个问题的方式…太好了!非常感谢你,暗影侠!你解决了我的问题。我很感激你回答这个问题的方式…太好了!