如何用 Python 將數字替換為字串?


為此,讓我們使用一個以數字為鍵,以其單詞表示形式為值的檔案物件 −

dct={'0':'zero','1':'one','2':'two','3':'three','4':'four',
     '5':'five','6':'six','7':'seven','8':'eight','9':'nine'

初始化一個 newstr 字串物件 

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.

更新時間: 20-Jun-2020

1 千次瀏覽量

啟動您的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.