初步格式
点击上传
X
给定一个字符串值(包含浮点值),我们必须在Python中将其转换为浮点值。
要将字符串值转换为float,我们使用float()功能。
float()function是python中的库函数,用于将给定的字符串或整数值转换为float值。
语法:
float(string_value/integer_value)
示例
Input: str = "10.23" print(float(str)) Output: 10.23 Input: str = "1001" print(float(str)) Output: 1001.0
Python代码将字符串转换为浮点值
# python代码演示示例 # float() function str1 = "10.23" str2 = "1001" # printing str1 & str2 types print("type of str1: ", type(str1)) print("type of str2: ", type(str2)) # 转换为浮点值 val1 = float(str1) val2 = float(str2) # printing types and values of val1 & val2 print("type of val1: ", type(val1)) print("type of val2: ", type(val2)) print("val1 = ", val1) print("val2 = ", val2)
输出结果
type of str1: <class 'str'> type of str2: <class 'str'> type of val1: <class 'float'> type of val2: <class 'float'> val1 = 10.23 val2 = 1001.0