Dragged on for so long, eventually defeated the lazy, opened the computer to write this blog, the content is very simple, Python implementation of the string to integer int method
Python has implemented the Int method, why do we have to write it again, just use it? This is true, but the int function seems to be simple, in fact, there are some pits
1. Judging positive or negative
This is easy to forget.
2.python cannot string subtraction
Python cannot directly use S-' 0 ' to directly implement a single-digit string-to-integer type like C + +, but instead needs to convert the ASCII code, Ord (s)-ord (' 0 ') to achieve the conversion
3. Determine if the limit is over
This is also the most easily ignored issue of the handwritten int function, the return result cannot be the limit of int, the maximum value of type int in Python is viewed using Sys.maxint. But the Python language is magical, and in fact Python's built-in int method has no result that must be less than the maxint limit
Here's my Python implementation
#!/use/bin/env python#_*_ coding:utf-8 _*_ImportSysmax_int=Sys.maxintnum_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 ()ifString.startswith ('-'): Is_minus=True String= String[1:] forSinchstring:ifS not inchnum_tuple:Print "Input Error" return0 Num= Ord (s)-Ord ('0') Total_num= Total_num * 10 +NumifTotal_num >Max_int:total_num=Max_int Break returnTotal_num *-1ifIs_minusElseTotal_num
Wishing all my friends and family all the best in health and good luck. I wish the beautiful Miss Alyssa, good academic success every day happy. Wish the Blog park more and better, I wish you a happy new year.
Python implements int function