Paul Paul - 1 month ago 5
Python Question

How do I convert unicode characters to floats in Python?

I am parsing a webpage which has Unicode representations of fractions. I would like to be able to take those strings directly and convert them to floats. For example:

"⅕" would become 0.2

Any suggestions of how to do this in Python?

Answer

You want to use the unicodedata module:

import unicodedata
unicodedata.numeric(u'⅕')

This will print:

0.20000000000000001

If the character does not have a numeric value, then unicodedata.numeric(unichr[, default]) will return default, or if default is not given will raise ValueError.