这题我先从后往前,3个为1组,生成数组。 然后针对一个数组,比如123这个数字,进行输出 最后有几个3位一组就分别对应百万,千,百
``` python []
def numtostr(f):
gw=["one","two","three","four","five","six","seven","eight","nine"]
xe=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]
sw=["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"]
s=''#用于计数,我是把他理解成字符串来做的
if len(f)==1:#转换成3位
f='00'+f
if len(f)==2:#转换成3位
f="0"+f
if len(f)==3:
if int(f[-2:])==0:#考虑100,200,300这种情况
s=s+" "+gw[int(f[0])-1]+" hundred"
else:
if int(f[0])!=0:
s=s+gw[int(f[0])-1]+" hundred and"
if 0<int(f[-2:])<=9:#解决01,02这种情况
s=s+" "+gw[int(f[-2:])-1]
elif 10<=int(f[-2:])<=19:#解决11,12,13~19这种情况
s=s+" "+xe[int(f[-2:])-10]
elif int(f[2])==0:#考虑个位数为0的这种情况,比如10,20,30等
s=s+" "+sw[int(f[1])-2]
else:
s=s+" "+sw[int(f[1])-2]+" "+gw[int(f[2])-1]
else:
if 0<int(f[-2:])<=9:#解决01,02这种情况
s=s+" "+gw[int(f[-2:])-1]
elif 10<=int(f[-2:])<=19:#解决11,12,13~19这种情况
s=s+" "+xe[int(f[-2:])-10]
elif int(f[2])==0:#考虑个位数为0的这种情况,比如10,20,30等
s=s+" "+sw[int(f[1])-2]
else:
s=s+" "+sw[int(f[1])-2]+" "+gw[int(f[2])-1]
return str(s).lstrip(" ")#最后还有把前面的空格去除
#numtostr("209")#测试用,测试一些特殊情况是否符合
while True:
try:
n=str(input())
#tmpnum=[]#每三位为一组
tmpnum=n[::-1]#先倒叙
tmp=[]
for j in range(0,len(tmpnum),3):
tmp.append("".join(tmpnum[j:j+3][::-1]))#然后负负得正
#3个一组得到的结果大概是这样的以1652510举例,得到结果为['510', '652', '1']
#print(tmp)
#numtostr("123")
if len(tmp)==1:#如果只有3位
print(numtostr(tmp[0]))#就直接打印,还得取首页空格
if len(tmp)==2:#如果超过3位就加thousand
print(numtostr(tmp[1])+" thousand "+numtostr(tmp[0]))
if len(tmp)==3:#如果超过6位就加million
print(numtostr(tmp[2])+" million "+numtostr(tmp[1])+" thousand "+numtostr(tmp[0]))
if len(tmp)==4:#
print(numtostr(tmp[2])+" billion "+numtostr(tmp[2])+" million "+numtostr(tmp[1])+" thousand "+numtostr(tmp[0]))
except:
break