Robert 830213
Robert 830213

Reputation: 19

How to replace number to string in python

I am tring to convert all the independent number to number's vocabulary in a given string,for example (I have 10 apples and 0 pencil) need to be converted to (I have 10 apples and zero pencil). However, I cannot directly assign string in list object, please help me, thanks! Here is my code, I am not very familier with python, thanks guys!

s = input()

for i in range(len(s)):
    if(s[i] == '0'):
        s[i] = "zero"
print(s) 

Upvotes: 0

Views: 870

Answers (4)

Raja Sarkar
Raja Sarkar

Reputation: 151

The simplest way is use of string replace function:

s = 'I have 10 apples and 0 pencil'
print (s.replace(' 0 ',' zero '))

The complicated way would be using re (you can use other ways to reach your desired string to be replaced):

import re
s = 'I have 10 apples and 0 pencil'
y = re.sub(r'( 0 )', ' zero ', s, count=1, flags=re.IGNORECASE)
print(y)

Upvotes: 1

Muhammad Ajwad
Muhammad Ajwad

Reputation: 9

    s = input()
    print(s.replace("0", "zero"))

Upvotes: 0

InspectorGadget
InspectorGadget

Reputation: 1000

You can use regular expression for this:

import re

txt = "I have 10 apples and 0 pencil"
x = re.sub(r"\b0\b", "zero", txt)
print(x)

this code gives you the output: I have 10 apples and zero pencil

Upvotes: 4

Toni Sredanović
Toni Sredanović

Reputation: 2402

Try with:

s.replace(" 0 ", " zero ")

Upvotes: 4

Related Questions