如何使用 Python 将数字替换为字符串?
为此,让我们使用一个字典对象,其中包含以数字为键,以单词表示值为值 -
dct={'0':'zero','1':'one','2':'two','3':'three','4':'four',
'5':'five','6':'six','7':'seven','8':'eight','9':'nine'初始化一个新的字符串对象
newstr=''
使用 for 循环遍历输入字符串中的每个字符 ch 并检查它是否使用 isdigit() 函数表示数字。
如果是数字,则将其用作键并从字典中找到相应的值,并将其附加到 newstr。如果不是,则将字符 ch 本身附加到 newstr。完整的代码如下
string='I have 3 Networking books, 0 Database books, and 8 Programming books.'
dct={'0':'zero','1':'one','2':'two','3':'three','4':'four',
'5':'five','6':'six','7':'seven','8':'eight','9':'nine'}
newstr=''
for ch in string:
if ch.isdigit()==True:
dw=dct[ch]
newstr=newstr+dw
else:
newstr=newstr+ch
print (newstr) 输出如预期
I have three Networking books, zero Database books, and eight Programming books.
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP