如何在Python中将包含“ /”的字符串转换为浮点数

O. *_*sen -6 python type-conversion python-3.x

我有一些尺寸以英寸格式输入为文本,例如:text =“ 20 7/8 16 1/4”#前两个表示长度,后两个表示宽度我可以更改此字符串使用text.split()转换为字符串列表以获取:[“ 20”,“ 7/8”,“ 16”,“ 1/4”]。

现在,我想将前两个项目20 + 7/8相加得到20.875。如何将7/8转换为浮点数?

小智 5

快速的Google搜索可以为您显示答案

from fractions import Fraction
print float(Fraction('7/8'))
Run Code Online (Sandbox Code Playgroud)