Python Implementation of converting strings into numbers

Source: Internet
Author: User

Python Implementation of converting strings into numbers
Python Implementation of converting strings into numbers

Python implementation that converts a string to a number, for example, converting a string "1234567.8" to 1234567.8

This is also a simple exercise in learning python. The Code is as follows:

# Coding = The UTF-8 converts a string to a number from functools import performanceimport mathdef char2int (s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9 ': 9} [s] def mulit_int (x, y): return 10 * x + ydef str2int (s): if s. find ('. ') =-1: # It is not a floating point return reduce (mulit_int, map (char2int, s) else: # It is a floating point s1 = s. split ('. ') s2int = reduce (mulit_int, map (char2int, s1 [0]) # integer part s2float = reduce (mulit_int, map (char2int, s1 [1]) * 0.1 ** len (s1 [1]) # return s2int + s2floatprint (str2int (123345.678 ))

The knowledge points mentioned above are the built-in map () and reduce () functions in python.

The map () function must receive two parameters. The first parameter is the function, and the second parameter is an Iterable object. The map function sequentially applies the input function to each element of the sequence, the result is returned as Iterable.

The reduce () function also receives two parameters, the same as map, but the reduce function continues to participate in the calculation of the result and the remaining elements in the sequence.

 

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.