python数字转汉字-Python转换数字到中文大写格式
今天有人在群里問到Python怎么把小寫數字轉換成中文的大寫字符,覺得這個問題很有趣,于是想了一下,就開始寫代碼了。
以下是代碼,感覺不足的地方就是如果是1001元,那么就會轉換成 壹仟零佰零拾壹圓,多了個零。這個代碼python2和python3都可以運行。
# -*- coding:utf-8 -*-
# date: 2018-02-28 11:48
def digital_to_chinese(digital):
str_digital = str(digital)
chinese = {"1": "壹", "2": "貳", "3": "叁", "4": "肆", "5": "伍", "6": "陸", "7": "柒", "8": "捌", "9": "玖", "0": "零"}
chinese2 = ["拾", "佰", "仟", "萬", "厘", "分", "角"]
jiao = ""
bs = str_digital.split(".")
yuan = bs[0]
if len(bs) > 1:
jiao = bs[1]
r_yuan = [i for i in reversed(yuan)]
count = 0
for i in range(len(yuan)):
if i == 0:
r_yuan[i] += "圓"
continue
r_yuan[i] += chinese2[count]
count += 1
if count == 4:
count = 0
chinese2[3] = "億"
s_jiao = [i for i in jiao][:3] # 去掉小于厘之后的
j_count = -1
for i in range(len(s_jiao)):
s_jiao[i] += chinese2[j_count]
j_count -= 1
last = [i for i in reversed(r_yuan)] + s_jiao
last_str = "".join(last)
print(str_digital)
print(last_str)
last_str = last_str.replace("0百", "0").replace("0十", "0").replace("000", "0").replace("00", "0").replace("0圓", "圓")
for i in range(len(last_str)):
digital = last_str[i]
if digital in chinese:
last_str = last_str.replace(digital, chinese[digital])
print(last_str)
return last_str
if __name__ == "__main__":
digital_to_chinese(123456789.456)
這是輸出
123456789.456
1億2仟3佰4拾5萬6仟7佰8拾9圓4角5分6厘
壹億貳仟叁佰肆拾伍萬陸仟柒佰捌拾玖圓肆角伍分陸厘
總結
以上是生活随笔為你收集整理的python数字转汉字-Python转换数字到中文大写格式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 跑monkey需要安装什么_安装隔音吊顶
- 下一篇: java学习路线_java学习路线_我的