python如何实现int函数的方法示例

yipeiwu_com6年前Python基础

前言

拖了这么久,最终还是战胜了懒惰,打开电脑写了这篇博客,内容也很简单,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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

Python中字符串的常见操作技巧总结

本文实例总结了Python中字符串的常见操作技巧。分享给大家供大家参考,具体如下: 反转一个字符串 >>> S = 'abcdefghijklmnop' >&...

python 远程统计文件代码分享

python 远程统计文件 #!/usr/bin/python #encoding=utf-8 import time import os import paramiko impor...

python 文件操作删除某行的实例

使用continue跳过本次写循环就可以了 #文本内容 Yesterday when I was young 昨日当我年少轻狂 The tasting of life was swe...

Python实现的根据IP地址计算子网掩码位数功能示例

Python实现的根据IP地址计算子网掩码位数功能示例

本文实例讲述了Python实现的根据IP地址计算子网掩码位数功能。分享给大家供大家参考,具体如下: #!/usr/bin/env python # coding:utf-8 #!/b...

python爱心表白 每天都是浪漫七夕!

python爱心表白 每天都是浪漫七夕!

本文为大家分享了python爱心表白的具体代码,供大家参考,具体内容如下 import turtle import time # 画爱心的顶部 def LittleHeart()...