我如何使用Python用字符串替换数字?
为此,让我们使用一个以数字为键,其单词表示为值的字典对象-
dct={'0':'zero','1':'one','2':'two','3':'three','4':'four',
'5':'five','6':'six','7':'seven','8':'eight','9':'nine'初始化一个新的字符串对象
newstr=''
在isdigit()函数的帮助下,使用for循环遍历输入字符串中的每个字符ch,以检查其是否为数字。
如果是数字,则将其用作键,然后从字典中找到相应的值并将其附加到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.
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语