0

I have already looked at other related stackoverflow answers to similar questions (Convert fraction to float?), ASCII encoding, etc, but have been unable to find something that solves the specific string issue I am encountering.

I have a string that contains this value '½', as well as other strings with mixed fractions such as '1 ½'. Passing these values through the fraction library or trying to remove the formatting that is being used results in errors such as

ValueError: Invalid literal for Fraction: '½'

Trying to use str.split("/") results in no change, passing

'½'.str.split("/") 

returns '½'.

Any tips on how to deal with these strings would be appreciated!

rye_bread
  • 95
  • 1
  • 3
  • 11
  • The fraction that you have given is a single Unicode character which means split will not work. `U+00BD` That is the reason it returns `½` itself. – Pro Chess Jan 20 '21 at 16:02
  • Interesting, I looked at ```U+00BD``` and it seems that it is a vulgar fraction? Is there a way of converting this to a numeric value? – rye_bread Jan 20 '21 at 16:08
  • I have created an answer. Please check if that satisfies what you expect. – Pro Chess Jan 20 '21 at 16:11
  • Does this answer your question? [Detect single string fraction (ex: ½ ) and change it to longer string?](https://stackoverflow.com/questions/49440525/detect-single-string-fraction-ex-%c2%bd-and-change-it-to-longer-string) – DarrylG Jan 20 '21 at 16:14

2 Answers2

2

Use the unicode data module. https://docs.python.org/3/library/unicodedata.html

>>> import unicodedata
>>> unicodedata.numeric(u'½')
0.5

I hope this helps you out.

Pro Chess
  • 831
  • 1
  • 8
  • 23
0
import unicodedata
unicodedata.numeric(frac)

Works great for this situation. For mixed fractions such as '1 ½', it is best to string split and then use unicodedata to convert this to numeric.

rye_bread
  • 95
  • 1
  • 3
  • 11