• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
MKT-porter
博客园    首页    新随笔    联系   管理    订阅  订阅
python:包含’e’和‘-’的 str 转 float
from functools import reduce

def str2float(s):
    s = s.split('.')
    a = s[0]
    b = s[1]
    if a[0] == '-':
        a = a[1:]
        front = reduce(lambda x,y:y+x*10,map(int,a))
        a = 0
        if 'e' in b:
            print('a')
            for i in b:
                a += 1
                if i == 'e':
                    c = b[a+1:]
                    middle = reduce(lambda x,y:y+x*10,map(int,c))
                    b = b[:a-1]
                    buttom = reduce(lambda x,y:y+x*10,map(int,b))
                    result = (front + buttom / 10 ** (len(b))) / 10 ** middle
                    result = -result
                    print(result)
                    return result
        else:
            print('b')
            buttom = reduce(lambda x, y: y + x * 10, map(int, b))
            result = front + buttom / 10 ** (len(b))
            result = -result
            print(result)
            return result
    else :
        front = reduce(lambda x, y: y + x * 10, map(int, a))
        a = 0
        if 'e' in b:
            print('c')
            for i in b:
                a += 1
                if i == 'e':
                    c = b[a+1:]
                    middle = reduce(lambda x,y:y+x*10,map(int,c))
                    b = b[:a-1]
                    buttom = reduce(lambda x,y:y+x*10,map(int,b))
                    result = (front + buttom / 10 ** (len(b))) / 10 ** middle
                    print(result)
                    return result
        else:
            print('d')
            buttom = reduce(lambda x, y: y + x * 10, map(int, b))
            result = front + buttom / 10 ** (len(b))
            print(result)
            return result

  

 

 

posted on 2023-03-02 21:27  MKT-porter  阅读(63)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3