Search code examples
pythonmysqlpython-3.xfloating-pointfractions

How to convert string with fraction to float in Python


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.

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.


Solution

  • >>> float(sum(fractions.Fraction(x) for x in unidecode.unidecode('100½').split()))
    100.5
    

    fractions

    unidecode