Python 如何将字符串转换为浮点数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38350482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:41:02  来源:igfitidea点击:

How to convert String into Float?

pythonpython-3.x

提问by itzRafay

I'm required to covert the variable:

我需要隐藏变量:

pi_string = "3.1415926"

into a float. Here's what I'm dealing with:

成一个浮动。这是我正在处理的:

screenshot

截屏

回答by Dean Fenster

Your line should be pi_float = float(pi_string)

你的线路应该是 pi_float = float(pi_string)

float(pi_string)is a float value, you can not assign to it, because it is not a variable.

float(pi_string)是一个浮点值,你不能赋值给它,因为它不是一个变量。

回答by Clíodhna

The method float()will do this for you if pi_string = "3.1415926".

该方法float()会为你如果做到这一点pi_string = "3.1415926"

>>>pi_float = float(pi_string)
>>>type(pi_float)
<class 'float'>