pythonstringreplacecharacterslice

Replacing reversed words in string, from list


Python

I have list with reversed words:

['rab', 'milb']

And i have a string with these words:

foo(bar)baz(blim)

How can i replace this words on reverted?

That's what i do:

a = "foo(bar)baz(blim)"
reversed_w = ['rab', 'milb']
for i in range(len(reversed_w)):
    pure_k = a.replace(reversed_w[i][::-1], reversed_w[i])

print(pure_k)

# what i expect: foo(rab)baz(milb)
# what i get: foo(bar)baz(milb)
# it happens cuz after first iteration it "foo(rab)baz(blim)", but
# because i dont know how to "remmember" that state of that string,
# after second iteration i get "foo(bar)baz(milb)", 
# cuz i am making that operation with unedited 
# string: "foo(bar)baz(blim)".

Ofcourse i can do it with slices, but its bruteforce. Imagine if i had 50 reversed words, and 1000 characters long string

I have searched replace in for loops, but didnt find anything


Solution

  • Your issue arises because you're resetting pure_k in each iteration of the loop. Instead, you should update the string a itself or use another variable to keep track of the changes across iterations:

    >>> a = "foo(bar)baz(blim)"
    >>> reversed_w = ['rab', 'milb']
    >>> for word in reversed_w:
    ...     a = a.replace(word[::-1], word)
    ... 
    >>> print(a)
    foo(rab)baz(milb)