I want write a function to convert string to float by using map and reduce. (no int() here). Here is my code so far:
from functools import reduce
def str2float(s):
def char2number(s):
s = s.replace('.', '')
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] #here i try to get pure numbers
def find_digt(s):
return (len(s) - s.find('.') - 1) if ',' in s else 0
return reduce(lambda x, y: (10 * x + y), (map(char2number, s))) / pow(10, find_digt(s))
print(str2float('1456.124'))
So after this, I get an error:
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[sn] # [s] is the [key]
KeyError: ''
Which means that the '' is not in the dict. I did some test like:
s = '1234.456'
s = s.replace(',', '')
print('' in s) #True
So the question now is, once
s = s.replace('.', '')
the '.' replace by '', it did not clear the '.' in the string.
I'm wondering what is going on here. what is the right way to clear a char in a string since it is immutable.