【问题标题】:KeyError:'.' when parsing a number as string键错误:'。'将数字解析为字符串时
【发布时间】:2018-03-23 09:09:11
【问题描述】:

当我运行我的代码时,它会产生一个KeyError

from functools import reduce   
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def str2float(s):
    dot_index=s.index('.')
    new_str = s[:dot_index]+s[dot_index:]
    print(new_str)
    return reduce(lambda x,y:x*10+y,map(lambda x:DIGITS[x],new_str))/(10**(len(new_str)-dot_index))

num = str2float('123.456')
print(num)

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    铸造浮动将解决您的问题:

        numberInString = "123.456"
        numberInFloat = float(numberInString)
    

    变量“numberInFloat”是一个浮点变量。 如果你想要一个整数,使用 int() 代替, str() 用于字符串。

    【讨论】:

      【解决方案2】:

      在解析stirng "123.456" 时,您的代码遇到了'.' 字符,该字符不在您的字典中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-12-27
        • 1970-01-01
        • 2013-04-23
        • 1970-01-01
        • 2018-08-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多