本文共 1256 字,大约阅读时间需要 4 分钟。
python字符串转浮点数
Using python it is very to interconvert the datatypes of a variable. A string can be easily converted to an integer or a float. However, asserting a string to be a float is a task by itself. Python provides an option to assert if a string is a float.
使用python可以相互转换变量的数据类型。 字符串可以轻松转换为整数或浮点数。 但是,断言一个字符串是一个浮点数本身就是一项任务。 Python提供了一个断言字符串是否为浮点数的选项。
Using the float() method, a variable can be type casted to a float variable. However, if the variable is not a valid float an exception is thrown.
使用float()方法 ,可以将变量类型转换为float变量。 但是,如果变量不是有效的float,则将引发异常。
Python 3.6.8 (default, Apr 25 2019, 21:02:35)[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linuxType "help", "copyright", "credits" or "license" for more information.>>> test_string = "45.02">>> print("The original string is {}".format(test_string))The original string is 45.02>>> try:... float(test_string)... print("{} is a valid float variable".format(test_string))... except:... print("invalid float variable")...45.0245.02 is a valid float variable>>> test_string = "aa">>> try:... float(test_string)... print("{} is a valid float variable".format(test_string))... except:... print("invalid float variable")...invalid float variable
翻译自:
python字符串转浮点数
转载地址:http://gfazd.baihongyu.com/