zoukankan      html  css  js  c++  java
  • Python不使用int()函数把字符串转换为数字

    Python不使用int()函数把字符串转换为数字

    方法一:利用str函数

    既然不能用int函数,那我们就反其道而行,用str函数找出每一位字符表示的数字大写。

    def atoi(s):
       s = s[::-1]
       num = 0
       for i, v in enumerate(s):
          for j in range(0, 10):
             if v == str(j):
                num += j * (10 ** i)
       return num

    方法二:利用ord函数

    利用ord求出每一位字符的ASCII码再减去字符0的ASCII码求出每位表示的数字大写。
    def atoi(s):
       s = s[::-1]
       num = 0
       for i, v in enumerate(s):
          offset = ord(v) - ord('0')
          num += offset * (10 ** i)
       return num

    方法三:利用eval函数

    eval的功能是将字符串str当成有效的表达式来求值并返回计算结果。我们利用这特点可以利用每位字符构造成和1相乘的表达式,再用eval算出该表达式的返回值就表示数字大写。
    def atoi(s):
       s = s[::-1]
       num = 0
       for i, v in enumerate(s):
          t = '%s * 1' % v
          n = eval(t)
          num += n * (10 ** i)
       return num
     

    例题如下:

    编写一个函数,实现:将字符串'12345'转换为[1, 2, 3, 4, 5], 再将列表值转换为整数12345,不使用内置的int(), str()函数。

    # string conbersion intager
    
    lst = []
    def Conversion(s):
        s = s[::-1]
        num = 0
        for i, v in enumerate(s):
            offset = ord(v) - ord('0')
            num += offset * (10 ** i)
            lst.append(offset)
    
        # lst conbersion intager
        number=0
        for k, v in enumerate(lst):
            number += v * (10**k)
    
        lst.reverse()
        print("string conbersion intager: 
     ",lst,"
    lst conbersion intager: 
     ",number)
    
    Conversion("12345")
  • 相关阅读:
    win10安装scrapy
    win10安装 pandas
    scrapy 启动失败,scrapy startproject test 出错 'module' object has no attribute 'OP_NO_TLSv1_1
    Mac环境下安装运行splash
    通过软链接解决目录空间不足的问题
    CentOS 图形界面的关闭与开启
    shell+crontab 实时服务进程监控重启
    Linux下查看yun rpm dpkg 软件是否安装成功的方法
    ubuntu设置root登录ssh
    Ubuntu的中文乱码问题
  • 原文地址:https://www.cnblogs.com/fengff/p/10483737.html
Copyright © 2011-2022 走看看