Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用下面提供的示例,将字符串百分比转换为浮点的干净方法是什么?_Python_String_Python 3.x_Floating Point - Fatal编程技术网

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))
。但是这不是已经在你链接的帖子中得到了回答吗?可能是重复的谢谢!我感谢你的反馈。暗影游侠(如下所示)用我可以使用的代码很好地解决了我的问题。非常感谢你的暗影游侠!你解决了我的问题。我很感激你回答这个问题的方式…太好了!非常感谢你,暗影侠!你解决了我的问题。我很感激你回答这个问题的方式…太好了!