I want to write a function to convert a string to float using a map and shortening. (there is no int ()). Here is my code:
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]
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 that I get the error message:
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[sn]
KeyError: ''
This means no in the dict. I did some tests like:
s = '1234.456'
s = s.replace(',', '')
print('' in s)
So the question is now, once
s = s.replace('.', '')
the. replace with '' he did not clear '.' in line.
I wonder what is going on here. that this is the right way to clear the char in a string since it is immutable.