当前位置:首页python > 正文

Python实现把数字转换成中文

作者:野牛程序员:2023-12-14 18:09:28python阅读 2830

数字转换成中文可以通过将数字每一位上的数字转换成对应的中文字符来实现。以下是一个简单的Python函数示例,可以将整数转换成中文表示:

def number_to_chinese(num):
    chinese_numerals = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
    unit_position = ['', '十', '百', '千']

    def convert_section(section):
        section_str = ''
        for i in range(len(section)):
            digit = int(section[i])
            if digit != 0:
                section_str += chinese_numerals[digit] + unit_position[len(section) - i - 1]
            elif i == len(section) - 1 or section[i + 1] != '0':
                section_str += chinese_numerals[digit]
        return section_str

    num_str = str(num)
    length = len(num_str)
    if length <= 4:
        return convert_section(num_str)
    elif length <= 8:
        return convert_section(num_str[:-4]) + '万' + convert_section(num_str[-4:])
    else:
        return convert_section(num_str[:-8]) + '亿' + convert_section(num_str[-8:-4]) + '万' + convert_section(num_str[-4:])

# 示例
result = number_to_chinese(123456789)
print(result)

这个函数可以将整数转换为中文表示,例如,123456789 被转换成 '一亿二千三百四十五万六千七百八十九'

野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击