+ 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?
9 Réponses
+ 2
First replace 10, then the single digits.
+ 4
Oh,thanks Lothar
+ 3
When the input is "10", your code will translate it to "onezero".
+ 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.
+ 1
Yes, you are right, how can I solve this problem?
+ 1
Thank you!
+ 1
Daniel ,
the sample code that you have posted creates an error in the last line (print(…)). the variable ‘f‘ is not declared.
+ 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