python如何实现int函数的方法示例
作者:熔遁丶螺旋手里剑 时间:2022-06-02 08:37:38
前言
拖了这么久,最终还是战胜了懒惰,打开电脑写了这篇博客,内容也很简单,python实现字符串转整型的int方法
python已经实现了int方法,我们为什么还要再写一遍,直接用不就好了?事实确实如此,但是int函数看似简单,实际上自己来实现还是有一些坑的
1.判断正负
这点很容易忘记
2.python不能字符串减法
python不能像c++一样直接使用s - '0'直接实现个位数的字符串转整型,而是需要转换ascii码,ord(s) - ord('0')来实现转换
3.判断是否超限
这也是手写int函数最容易忽略的问题,返回结果不能出int的限制,python中int类型的最大值使用sys.maxint
查看。但是python语言很神奇,实际上python内置的int方法并没有结果必须小于maxint的限制
下面给出我的python实现
#!/use/bin/env python
# _*_ coding:utf-8 _*_
import sys
max_int = sys.maxint
num_tuple = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
def _int(input_string):
total_num = 0
is_minus = False
string = input_string.strip()
if string.startswith('-'):
is_minus = True
string = string[1:]
for s in string:
if s not in num_tuple:
print "input error"
return 0
num = ord(s) - ord('0')
total_num = total_num * 10 + num
if total_num > max_int:
total_num = max_int
break
return total_num * -1 if is_minus else total_num
来源:http://www.cnblogs.com/baiyb/p/8452993.html
标签:python,int函数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
高效地获取XMLhttp对象
2010-01-19 13:49:00
如何做迅雷电影提示效果
2011-03-31 17:15:00
PHP数据库表操作的封装类及用法实例详解
2023-11-12 07:41:23
使用python遍历指定城市的一周气温
2022-01-01 18:25:26
页面重构应注意的repaint和reflow
2011-03-31 17:11:00
Ajax的错误处理机制探讨
2007-09-07 09:53:00
两个元祖T1=('a', 'b'),T2=('c', 'd')使用匿名函数将其转变成[{'a': 'c'},{'b': 'd'}]的几种方法
2023-06-25 12:44:15
回调函数的意义以及python实现实例
2021-07-17 11:42:07
Python使用爬虫猜密码
2023-03-21 12:38:39
![](https://img.aspxhome.com/file/2023/6/67766_0s.png)
Python使用minidom读写xml的方法
2022-03-14 11:35:22
Python使用列表和字典实现简单的考试系统详解
2023-11-07 11:14:53
ASP提速技巧五则
2008-03-20 13:20:00
ASP链接Mysql数据库 非DSN连接的方法
2009-03-09 18:24:00
python爬虫headers设置后无效的解决方法
2021-09-04 00:55:17
![](https://img.aspxhome.com/file/2023/9/79609_0s.png)
window.location.hash的应用及浏览器的支持测试
2009-07-07 11:52:00
![](https://img.aspxhome.com/file/UploadPic/20097/7/hashdemo-57s.png)
Python BeautifulReport可视化报告代码实例
2023-11-12 14:53:13
![](https://img.aspxhome.com/file/2023/4/64314_0s.png)
Python 计算任意两向量之间的夹角方法
2022-11-10 07:01:47
![](https://img.aspxhome.com/file/2023/7/72787_0s.jpg)
Javascript中的isNaN函数使用说明
2023-08-27 10:10:02
SQL语句的执行原理分析
2012-01-29 18:17:36
使用Python处理json字符串中的非法双引号问题
2021-01-19 19:26:13