Kelvin Davis Kelvin Davis - 5 months ago 29
Python Question

Replacing strings, not characters without the use of .replace and joining the strings the characters

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

that replaces it:

def replace(a, b, c):
new = b.split()
result = ''
for x in new:
if x == a:
x = c
result +=x
print(' '.join(result))

Calling it with:

replace('dogs', 'I like dogs', 'kelvin')

My result is this:

i l i k e k e l v i n

What I'm looking for is:

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 list , append to it (it's also faster than using += on strings) and print it out by unpacking it.

That is:

def replace(a, b, c):
    new = b.split(' ')
    result = []
    for x in new:
        if x == a:
            x = c

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.