Discuss / Python / 去除非数字字符

去除非数字字符

Topic source

勇猛熊猫

#1 Created at ... [Delete] [Delete and Lock User]

-- coding: utf-8 --

from functools import reduce

def char2num(s): return {'0':0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}.get(s)

def str2int(s): return reduce(lambda x, y: 10 * x + y if isinstance(y, int) else x, map(char2num, '0' + s))

def str2decimal(s): return reduce(lambda x, y: x / 10 + y if isinstance(y, int) else x, map(char2num, '0' + s[::-1])) / 10

def str2float(s): if s.find('.') > -1: return str2int(s.split('.', 1)[0]) + str2decimal(s.split('.', 1)[1]) return str2int(s)


  • 1

Reply