Reputation: 19
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
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
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