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.