网站首页 > 技术文章 正文
将数字转化为中文1到9的两种方法
方法一:可以通过列表list的方法,即将1到9的中文作为元素,构建出一个列表list,然后根据用户的输入(1到9之间的数字),转换为int整型,然后减去1作为索引,因为索引从0开始,然后根据索引访问列表中对应的元素。
方法二:使用字典进行映射,其中1到9作为键,1到9的中文作为键对应的值,然后便可应根据用户的输入,来访问对应键中的值,该方法不需要对输入的数据进行类型的转换。
列表方法实例代码
使用到的函数:input()、replace()、int():
#-*- coding:utf-8 -*-
def num2utf8_list():
num_list = ["一","二","三","四","五","六","七","八","九"]
num_str = input("请输入1到9的数值:")
num = int(num_str.replace(" ",""))
index = num-1
return num_list[index]
num = num2utf8_list()
print(num)
运行python文件,得到输出:
请输入1到9的数值:6
六
字典dict方法
使用到的函数:input()、replace():
#-*- coding:utf-8 -*-
def num2utf8_dict():
num_dict = {"1":"一","2":"二","3":"三","4":"四","5":"五","6":"六","7":"七","8":"八","9":"九"}
num_str = input("请输入1到9的数值:")
return num_dict[num_str.replace(" ","")]
num = num2utf8_dict()
print(num)
运行文件得到输出:
请输入1到9的数值:5
五
猜你喜欢
- 2025-05-08 Python注释(多行注释和单行注释)用法详解
- 2025-05-08 Python小案例65- 猜数字游戏(python编程简单的猜数字游戏)
- 2025-05-08 python自学者的分享:键盘输入、列表、元组、多维容器
- 2025-05-08 Python 数字和转换(python 转换成数字)
- 2025-05-08 编写一个自动生成双色球号码的 Python 小脚本
- 2025-05-08 数字、字符串和变量:如何使用python三大基本元素,基础很重要
- 2025-05-08 python经典案例:猜数字游戏(python编程简单的猜数字游戏)
- 2025-05-08 用python写游戏之200行代码写个数字华容道
- 2025-05-08 Python实现【数字游戏】(python数字游戏代码)
- 2025-05-08 Python实现数值型与字符型类别变量的独热编码One-hot Encoding
- 263℃Python短文,Python中的嵌套条件语句(六)
- 262℃python笔记:for循环嵌套。end=""的作用,图形打印
- 261℃PythonNet:实现Python与.Net代码相互调用!
- 255℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 255℃Python实现字符串小写转大写并写入文件
- 113℃原来2025是完美的平方年,一起探索六种平方的算吧
- 94℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 87℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)