ใช้ dictionary mapping ตัวเลขเป็นคำอ่าน:
dct = {'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four',
'5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'}
วนลูปแต่ละตัวอักษร ตรวจสอบด้วย isdigit() ถ้าเป็นตัวเลข ใช้ dictionary mapping แทนที่:
string = 'I have 3 Networking books, 0 Database books, and 8 Programming books.'
newstr = ''
for ch in string:
if ch.isdigit():
newstr += dct[ch]
else:
newstr += ch
print(newstr)
ผลลัพธ์
I have three Networking books, zero Database books, and eight Programming books.