Python implements int function

Source: Internet
Author: User
Tags ord

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.