Question has been asked that is similar but all post on here refer to replacing single characters. I'm trying to replace a whole word in a string. I've replaced it but I cant print it with spaces in between.
Here is the function
def replace(a, b, c):
new = b.split()
result = ''
for x in new:
if x == a:
x = c
replace('dogs', 'I like dogs', 'kelvin')
i l i k e k e l v i n
I like kelvin
The issue here is that
result is a string and when
join is called it will take each character in
result and join it on a space.
Instead, use a
append to it (it's also faster than using
+= on strings) and print it out by unpacking it.
def replace(a, b, c): new = b.split(' ') result =  for x in new: if x == a: x = c result.append(x) print(*result)
print(*result) will supply the elements of the
result list as positional arguments to print which prints them out with a default white space separation.
"I like dogs".replace("dogs", "kelvin") can of course be used here but I'm pretty sure that defeats the point.