How i can replace number with string using Python?

PythonWX Python

For this purpose let us use a dictionary object having digit as key and its word representation as value −

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

Initializa a new string object 

newstr=''

Using a for loop traverse each character  ch from input string at check if it is a digit with the help of isdigit() function. 

If it is digit, use it as key and find corresponding value from dictionary and append it to newstr. If not append the character ch itself to newstr. Complete code is as follows:

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)      

The output is as desired

I have three Networking books, zero Database books, and eight Programming books.
raja
Published on 02-May-2018 10:31:57
Advertisements