'Python returns "invalid character in identifier" when input a fraction [duplicate]
Is there a way (some library) that can correctly identify ½ -0.2 as valid input? It appears that the ½,¼,¾ characters are not recognized by Python.
I searched the net extensively but couldn't find an answer.
Solution 1:[1]
You can use the unicodedata module from the standard library:
import unicodedata
print(unicodedata.numeric('¼'))
Output:
0.25
Solution 2:[2]
Those characters are unicode symbols, python does not support casting those symbols to float or int by default.
To workaround this you can map the float representation of those characters using a dict
divisor_map = {½: 0.5, ¼: 0.25...}
You can then check if the input is in the map, and substitute it accordingly
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wjandrea |
| Solution 2 | CoderWithADream |
