如何使用 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.

更新日期:20-Jun-2020

1K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.