+ 1

I write a python code for "Take a phrase and replace any instances of an integer from 0-10 and replace it with the English word.

``` def replace_numbers(phrase): numbers = { '0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '10': 'ten' } for key, value in numbers.items(): phrase = phrase.replace(key, value) return phrase phrase = input() print(replace_numbers(phrase)) ``` My code is perfect and solves that problem but it is right with 5 conditions not all six, Why?

17th Feb 2025, 12:28 PM
Manish Kumar
Manish Kumar - avatar
9 Réponses
+ 2
First replace 10, then the single digits.
17th Feb 2025, 12:51 PM
Lisa
Lisa - avatar
+ 4
Oh,thanks Lothar
18th Feb 2025, 11:49 AM
Daniel
Daniel - avatar
+ 3
When the input is "10", your code will translate it to "onezero".
17th Feb 2025, 12:39 PM
Lisa
Lisa - avatar
+ 2
Manish Kumar , a different approach that solves the issue of replacing the number 10 (and some others): read the input-string, and split it into chunks by using the spaces as a separator. then iterate over the resulting list of the mentioned step and do the replacement.
17th Feb 2025, 4:00 PM
Lothar
Lothar - avatar
+ 1
Yes, you are right, how can I solve this problem?
17th Feb 2025, 12:46 PM
Manish Kumar
Manish Kumar - avatar
+ 1
Thank you!
17th Feb 2025, 1:00 PM
Manish Kumar
Manish Kumar - avatar
+ 1
Daniel , the sample code that you have posted creates an error in the last line (print(…)). the variable ‘f‘ is not declared.
18th Feb 2025, 10:13 AM
Lothar
Lothar - avatar
+ 1
A variation on Daniel's code that still applies Lothar's approach. 1 - create list instead of dictionary of the string version of numbers. 2 - when looping over the list of strings created by splitting phrase, check if string is just numerals with isnumeric() 3 - convert to int and if 10 or less, use as index for list to get string version of numbers. 4 - can overwrite the entry in phrase list instead of appending to new list https://sololearn.com/compiler-playground/cJmSYLmxU3TM/?ref=app
20th Feb 2025, 8:16 PM
Shardis Wolfe