如何在Python中将带分数的字符串转换为浮点数 [英] How to convert string with fraction to float in Python
本文介绍了如何在Python中将带分数的字符串转换为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在准备一些要插入MySQL的数据.不幸的是,某些数据的格式为100½
.我需要将其转换为浮点数,但显然 float(100½)
失败.
I'm prepping some data to insert into MySQL. Unfortunately some of the data is in the form 100½
. I need to convert this to a float, but obviously float(100½)
fails.
Python中是否有一种方法可以处理此转换?我不反对对某些东西进行硬编码,但将来可能会遇到⅝
或其他分数.
Is there a method in Python that can handle this conversion? I'm not opposed to hard coding something, but I may encounter ⅝
or other fractions in the future.
推荐答案
>>> float(sum(fractions.Fraction(x) for x in unidecode.unidecode('100½').split()))
100.5
这篇关于如何在Python中将带分数的字符串转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文