Python does not use the Int () function to convert a string to a number

Source: Internet
Author: User
Tags ord

Converts a string to a number without using the Int () function, such as converting the string "12345" to the number 12345. method One: Using the str function

Since we can't use the INT function, we're going to go against it and use the STR function to find out the number of digits represented by each character.

Atoi (s):
   s = s[::-1]
   num = 0
   Enumerate (s):
      Range (0)
         :  v = = str (j):
            num + + J * (* * i)
   num

method Two: Use the Ord function to find the ASCII code of each character and subtract the ASCII code of character 0 to find out the number of digits represented by the Ord.

Atoi (s):
   s = s[::-1]
   num = 0
   Enumerate (s):
      offset = ord (v)-ord (' 0 ')
      num + + offset * (i)
   num

method Three: Use the Eval functionThe Eval function evaluates the string str as a valid expression and returns the result of the calculation. We can use this feature to create an expression that multiplies 1 by each character, and then use eval to calculate the return value of the expression to denote the number of uppercase.
Atoi (s):
   s = s[::-1]
   num = 0
   Enumerate (s):
      t = '%s * 1 '% v
      n = eval (t)
      num = n * (i)
   num

Related Article

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.