0

The wonders of Python!!

Hi guys, this code converts the numbers inside the text to words, but a problem occurs with number 10 at the end of the string! This is more interesting that if we change the first number of the string (1), to 10, the problem will be solved! Can someone explain that?! import re str1 = "1 plus 2 plus 3 p 4 p 5 p 6 p 7 p 8 p 9 p 10" nums = {"1": "one", "2": "two", "3": "three", "4": "four", "5": " five", "6": "six", "7": "seven", "8": "eight", "9": "nine", "10": "ten"} d = re.findall('\d+', str1 ) t = tuple(d) def rep(x, t): l = len(t) i = 0 for i in range(0, l + 2): if i == l: return x elif i < l: if t[i] in x: x = x.replace(t[i], nums[t[i]]) i += 1 print(rep(str1, t))

16th Jul 2020, 11:26 PM
Mohammad Moharrami
Mohammad Moharrami - avatar
3 Respostas
+ 2
Mohammad Moharrami Problem is that you used replace which will replace all 1's with "one" so next time 10 will not come in String because it already replaced by one like one0. For example: str1.replace(1, "one") Here all 1's will be replace by one so on next iteration 10 will not come.
17th Jul 2020, 2:07 AM
A͢J
A͢J - avatar
0
so why in this code everything is ok? import re str1 = "10 plus 2 plus 3 p 4 p 5 p 6 p 7 p 8 p 9 p 10" nums = {"1": "one", "2": "two", "3": "three", "4": "four", "5": " five", "6": "six", "7": "seven", "8": "eight", "9": "nine", "10": "ten"} d = re.findall('\d+', str1 ) t = tuple(d) def rep(x, t): l = len(t) i = 0 for i in range(0, l + 2): if i == l: return x elif i < l: if t[i] in x: x = x.replace(t[i], nums[t[i]]) i += 1 print(rep(str1, t))
17th Jul 2020, 10:26 AM
Mohammad Moharrami
Mohammad Moharrami - avatar
0
Anyway I solved the problem, thanks Anant 🙏🏻
17th Jul 2020, 2:47 PM
Mohammad Moharrami
Mohammad Moharrami - avatar