Python不使用int()函数把字符串转换为数字的方法
作者:xiemanR 时间:2022-04-22 02:32:33
不使用int()函数的情况下把字符串转换为数字,如把字符串"12345"转换为数字12345。
方法一:利用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
来源:https://blog.csdn.net/xiemanR/article/details/72824606
标签:Python,字符串,数字
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python while、for、生成器、列表推导等语句的执行效率测试
2021-03-05 02:17:54
PHP操作MySQL中BLOB字段的方法示例【存储文本与图片】
2023-11-23 23:45:27
W3C优质网页小贴士(一)
2008-04-06 16:35:00
![](https://img.aspxhome.com/file/UploadPic/up/2008040712541063.gif)
轻松掌握python设计模式之策略模式
2022-01-19 00:17:15
![](https://img.aspxhome.com/file/2023/3/67843_0s.jpg)
Oracle数据库的十种重新启动步骤
2012-07-21 14:58:25
js求一组数中的最大数
2008-04-10 12:00:00
python贪吃蛇游戏代码
2023-07-22 04:19:17
![](https://img.aspxhome.com/file/2023/3/60493_0s.jpg)
numpy 声明空数组详解
2022-09-20 15:29:44
使用Python实现图像标记点的坐标输出功能
2022-10-31 16:15:06
![](https://img.aspxhome.com/file/2023/9/68839_0s.jpg)
ORACLE数据库事务隔离级别介绍
2012-10-07 10:43:36
详解python程序中的多任务
2021-01-10 18:55:37
![](https://img.aspxhome.com/file/2023/6/68876_0s.gif)
httpwatch 的页面元素加载时间表
2008-02-13 08:28:00
![](https://img.aspxhome.com/file/UploadPic/20082/13/200821383430675s.gif)
Golang 使用http Client下载文件的实现方法
2023-07-21 07:32:23
查询数据表中的记录(SELECT)
2009-02-27 16:06:00
Python Unittest自动化单元测试框架详解
2023-09-13 23:13:56
![](https://img.aspxhome.com/file/2023/2/67822_0s.png)
python 获取网页编码方式实现代码
2023-07-21 08:15:14
python买卖股票的最佳时机(基于贪心/蛮力算法)
2022-12-26 14:44:24
![](https://img.aspxhome.com/file/2023/1/76891_0s.png)
Python编程中的文件操作攻略
2022-12-08 10:49:54
![](https://img.aspxhome.com/file/2023/1/72121_0s.jpg)
MySQL权限分配
2011-01-29 16:37:00
JavaScript的目的及历史
2007-10-17 18:53:00