题解 | #人民币转换#
人民币转换
http://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b
这题单纯的条件比较多
num = input()
intpart, floatpart = num.split('.') # 小数点前后分开处理
length = len(intpart) # 整数部分长度
resStr = "人民币"
if num == 0:
print("人民币零元整")
rmbDict = {1:'壹', 2:'贰', 3:'叁', 4:'肆', 5:'伍',
6:'陆', 7:'柒', 8:'捌', 9:'玖'}
powDict = {1:'拾', 2:'佰',3:'仟'}
count = length # 小数点前的位置
# *********** 先写小数点前 ***********
preZeroFlag = False # 初始化0标记
while count > 0:
currNumStr = num[length - count] # 当前数字,字符形式
currNum = int(currNumStr)
if length == 1 and currNum == 0: # 若整数部分为0则只写小数部分
break
# 根据规则写字符串
if currNum == 0:
preZeroFlag = True
elif currNum != 0:
# 若前面有0则加入汉字零
if preZeroFlag == True:
if count == 4: # 规则5:千前面有0不加零
continue
else:
resStr += '零'
preZeroFlag = False
# 万位、亿位、个位元单独处理
if count == 5:
resStr += (rmbDict[currNum] + '万') # 万
elif count == 9:
resStr += (rmbDict[currNum] + '亿') # 亿
elif count == 1:
resStr += (rmbDict[currNum]) # 个位元
else:
# 取余
if count > 8:
countMod = (count - 1) % 8
else:
countMod = (count - 1) % 4
if currNum == 1 and countMod == 1: # 规则4:10写作拾
resStr += '拾'
else:
resStr += (rmbDict[currNum] + powDict[countMod])
count -= 1
if count == 0: # 整数部分写完加汉字'元'
resStr += '元'
# *********** 再写小数点后 ***********
if floatpart[0] == '0' and floatpart[1] == '0':
resStr += '整'
elif floatpart[0] == '0' and floatpart[1] != '0':
resStr += rmbDict[int(floatpart[1])] + '分'
elif floatpart[0] != '0' and floatpart[1] == '0':
resStr += rmbDict[int(floatpart[0])] + '角'
else:
resStr += rmbDict[int(floatpart[0])] + '角' + rmbDict[int(floatpart[1])] + '分'
print(resStr)