我如何使用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.
热门推荐
1 狗狗下楼训练
3 狗狗训练头盔
6 狗狗训练机构
7 训练狗狗步骤
9 狗狗能训练
10 狗狗基本动作训练方法
11 怎么训练狗狗叼饭盆
12 狗狗一岁了还能训练吗
13 训练狗狗的
14 宁波狗狗训练
15 训练狗狗拉屎
16 教狗狗训练
17 狗狗要怎么训练上厕所
18 狗狗靠的训练