我如何使用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 红包祝福语简短10字
18 周六早晨祝福语简短