Python 數字字串轉數字
3 min readFeb 9, 2021
關鍵字: Python、數字字串、轉數字、浮點數、小數
如題,因為 input 字串會有一些特別符號,不能直接用內建的 api 直接做轉換(ex: $ 1,234.00),所以寫了以下功能,給大家參考~
import reDIGIT_TABLE = u'[〇○01234567890-9.]'
DELIM = u'[圓元正整NT$,xX#※*-]'
DELIM_DOT = u'[.]'def small_amount_convert(input_str):
if input_str == '':
return input_str s_amount_list = [x for x in re.split(DELIM, input_str) if x is not '']
filtered_str = ''
for i in s_amount_list:
filtered_str += i for i in range(len(filtered_str)):
tmp_zh = filtered_str[i]
pattern = re.compile(DIGIT_TABLE)
ret = pattern.search(tmp_zh) if ret == None:
return "fail: " + input_str ret_str = ''
# 處理最後一個逗號以前的數字
for i in s_amount_list[:-1]:
if re.findall(DELIM_DOT, i):
split_dot_list = [x for x in re.split(DELIM_DOT, i) if x is not '']
for j in split_dot_list:
if ret_str == None or len(j) == 3:
ret_str += j
else:
return "fail: " + input_str
else:
ret_str += i # 處理最後一個逗號以後的數字
if re.findall(DELIM_DOT, s_amount_list[-1]):
split_dot_list = [x for x in re.split(DELIM_DOT, s_amount_list[-1]) if x is not ''] # 處理最後一個逗點以前的數字
for j in split_dot_list[:-1]:
ret_str += j # 處理最後一個逗點以後的數字
if split_dot_list and split_dot_list[-1] != '':
if len(split_dot_list[-1]) <= 2:
if int(split_dot_list[-1]) != 0:
return "fail: " + input_str
else:
ret_str += split_dot_list[-1]
else:
ret_str += s_amount_list[-1]return ret_str