表示浮点数的字符串

String that represents float to fraction

我正在尝试处理这样的字符串:

s = '1/2.05'

当我尝试将其解析为分数时:

Fraction(s)

我正在获得:

ValueError: ("Invalid literal for Fraction: u'1/2.05'", u'occurred at index 3')

我也试过:

Fraction(s.split('/')[0], s.split('/')[1])

但也有错误:

TypeError: ('both arguments should be Rational instances', u'occurred at index 3')

正确的解析是怎样的?

提前谢谢大家!

问题在于分数和浮点数不能混合,因此您不能直接转换在分数中隐藏浮点数的字符串。

不过不要为此使用 eval。
尝试分别处理分子和分母。 (您可以使用浮点数,但直接调用字符串上的 Fraction 会更精确,避免 precision issues。)

from fractions import Fraction
s = '1/2.05'
numerator, denominator =  s.split('/')
result = Fraction(numerator)/Fraction(denominator)
print(result)