0

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) 
3
  • 4
    s.replace("0", "zero") Commented May 29, 2021 at 7:34
  • Thanks but how to remain 10 as 10 Commented May 29, 2021 at 7:38
  • why 10 not convert to ten? Commented May 29, 2021 at 7:57

4 Answers 4

4

Try with:

s.replace(" 0 ", " zero ")
Sign up to request clarification or add additional context in comments.

1 Comment

It doesn't work if "0" is at the beginning like "0 apple" or at the end like "number of pencil is 0".
4

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

Comments

1

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)

Comments

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

1 Comment

This code also changes 10 to 1zero which is not what the OP wants.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.