replace string one by one in python

Advertisements

I have a string and I need to replace "e" with "x" one at a time. For e.g.

x = "three"

Then the expected output is:

("thrxe", "threx")

and if I have 3 characters to replace, for e.g.

y = "threee"

Then the expected output will be

("thrxee", "threxe", "threex")

I have tried this:

x.replace("e", "x", 1)
'thrxe'

But not sure how to return the second string "threx"

>Solution :

Try this

x = "threee"
# build a generator expression that yields the position of "e"s
# change "e"s with "x" according to location of "e"s yielded from the genexp
[f"{x[:i]}x{x[i+1:]}" for i in (i for i, e in enumerate(x) if e=='e')]
['thrxee', 'threxe', 'threex']

Leave a ReplyCancel reply