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提供了一個斷言字符串是否為浮點數的選項。
浮動() (float())
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 linux
Type "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.02
45.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
翻譯自: https://www.includehelp.com/python/how-do-i-check-if-a-string-is-a-number-float-in-python.aspx
python字符串轉浮點數