如何在 Python 中將數字轉換為單詞


在 Python 中,字串類 str 的建構函式可用於將數字轉換為 Python 中的字串。例如,

i = 10050
str_i = str(i)
print(type(str_i))

將會給出輸出

<class 'str'>

但是,如果你希望 將整數轉換為單詞,例如將 99 轉換為九十九,則必須使用外部程式包或自己構建一個。pynum2word 模組非常適合此任務。你可以使用以下方法進行安裝

$ pip install pynum2word

然後以以下方式使用

>>> import num2word
>>> num2word.to_card(16)
'sixteen'
>>> num2word.to_card(23)
'twenty-three'
>>> num2word.to_card(1223)
'one thousand, two hundred and twenty-three'

更新時間: 2020 年 6 月 17 日

1K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告