欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用python实现金额转换,阿拉伯数字的金额转换成中国传统的形式,如:(¥1011)→(壹仟零壹拾壹元整)输出。

程序员文章站 2022-06-18 08:50:24
...
x={1: '壹', 2: '贰', 3: '叁', 4: '肆', 5: '伍',6:'陆',7:'柒',8:'捌',9:'玖',0:'零'}
y=("元","拾","佰","仟","万","拾","佰","仟","亿","拾","佰","仟","万","拾","佰","仟")
c=[]
d=""

n= input("请输入一个大于零不超过十五位的数字:")
while len(n)>15 or  int(n)<=0:
  n=input("输入错误,请重新输入一个大于零不超过15位的数字")

k=len(n)-1
for i in n:
  j=int(i)
  c.append(x[j])
  c.append(y[k])
  k=k-1

k=len(c)-1
for i in range(k,0,-2):
   if c[i-1]=="零":
     c[i-1]="x"
   if c[i]!="元" and c[i]!="万" and c[i]!="亿" and c[i-1]=="x":
     c[i]="x"

for i in range(k,0,-1):
   if (c[i]=="元" or c[i]=="万" or c[i]=="亿") and c[i-1]=="x" or c[i]=="y" and c[i-1]=="x":
     c[i-1]="y"

k=len(c)-2
for i in range(k,0,-1):
   if c[i]=="x" and c[i+1]!="零" and c[i+1]!="x":
     c[i]="零"

k=len(c)
if k>=18 and c[k-16]=="y" and  c[k-14]=="y" and c[k-12]=="y":
  c[k-9]="x"

i=0
for i in range(i,len(c)):
  if c[i]!="x" and c[i]!="y":
     d=d+c[i]

print(d)