我试图处理这样的字符串:
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进行此操作。
试着分别处理分子和分母。(可以使用float,但是直接调用字符串上的分数更精确,避免了precision issues)
相关问题 更多 >
编程相关推荐