python---字符串转float or int

字符串转 整型或者 浮点型

“12.2” -> 12.2
“12” -> 12

def str_to_float(s):
    data = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, ".": "."}
    if "." in s:
        _num = 0
        zheng, xiao = s.split(".")
        l = len(zheng) - 1

        for i in zheng:
            num = data.get(i)
            num = num * 10 ** l
            l -= 1
            _num += num

        l = 1
        for i in xiao:
            num = data.get(i)
            num = num / (10 ** l)
            l += 1
            _num += num
        return _num
    else:
        _len = len(s)
        _num = 0
        l = _len - 1
        for i in s:
            num = data.get(i)
            num = num * 10 ** l
            l -= 1
            _num += num
        return _num


print(str_to_float("12.12"))

你可能感兴趣的:(python)