表示浮点到分数的字符串

2024-09-27 07:21:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图处理这样的字符串:

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')

正确的解析是什么?你知道吗

提前谢谢大家!你知道吗


Tags: 字符串forindex错误分数atsplitvalueerror
1条回答
网友
1楼 · 发布于 2024-09-27 07:21:06

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

但不要使用eval进行此操作。
试着分别处理分子和分母。(可以使用float,但是直接调用字符串上的分数更精确,避免了precision issues

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

相关问题 更多 >

    热门问题