Find and replace a word in a string and count how many replacements occurred? What’s the wrong in my code or any solution? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Find and replace a word in a string and count how many replacements occurred? What’s the wrong in my code or any solution?

text = "Amy has 128 dollars, while David has 54 dollars. Amy is going to the zoo. David watches soccer." f = input() r = input() c =0 while(text.find(f))!= -1: text = text.replace(f,r) for w in text.split(): if w == r: c = c +1 print(c) print(text)

15th Feb 2022, 1:11 AM
Md.Delwar Hossain
Md.Delwar Hossain - avatar
2 Answers
+ 6
Md.Delwar Hossain First count then replace. also in case of text.split() will not work because in this case "dollars," or "dollars." would be considered as a string means comma and dot will also be join with string so 'dollars' == 'dollars,' # would be false So Simply you can use count function and replace function directly without loop print (text.count(f)) print (text.replace(f, r))
15th Feb 2022, 2:31 AM
A͢J
A͢J - avatar
0
Thanks. My problem is I always think complex way where there is a simple solution available.
15th Feb 2022, 10:45 AM
Md.Delwar Hossain
Md.Delwar Hossain - avatar