1. 程式人生 > >python 轉換數字為錢數

python 轉換數字為錢數

目標:

輸入一串數字,將其輸出為幾元幾角幾分

程式:

#!/usr/bin/env python
#coding:utf8

num_dict = {'1':'一','2':'二','3':'三','4':'四','5':'五',
            '6':'六','7':'七','8':'八','9':'九'}
money_dict = {'-2':'分','-1':'角','0':'元','1':'十',
            '2':'百','3':'千','4':'萬','8':'億'}

def trans(money):
    money_str = []
    for index,value in enumerate(money[0][::-1]):
        remain = index%4
        if value != '0':
            if remain != 0:
                money_str.insert(0,num_dict[value]+money_dict[str(remain)])
            else:
                money_str.insert(0,num_dict[value]+money_dict[str(index)])
 18         elif remain == 0 and (index+1) != len(money[0]):
 19             money_str.insert(0,money_dict[str(index)])
 20     if len(money) > 1:
 21         for index,value in enumerate(money[1]):
 22             if index > 1:
 23                 break
 24             if value != 0:
 25                 money_str.append(num_dict[value]+money_dict['-'+str(index+1)])
 26     print ''.join(money_str)
 27
 28 def main():
 29     input_str = raw_input('Entry your money:')
 30     money = input_str.split('.')
 31     trans(money)
 32
 33 if __name__ == '__main__':
 34     main()

結果: