3

I want to replace each instance of a character in one string with a character at the same index in another string. If no character exists at that index, leave it as it is.

Here's my solution with a list comprehension (Python 3):

string1 = "food is delicious"
string2 = "orange is not delicious"
string3 = "".join([string2[i] if i<len(string2) and c=="o" else c for i, c in enumerate(string1)])
print(string3)

Result

frad is delicidus

It feels like there should be a better way though, for example using str.replace somehow. Any ideas?

2 Answers 2

2

You can itertools.zip_longest to iterate both the strings, till the longest of the them is exhausted. The smaller string will be filled with fillvalue

>>> s1 = "food is delicious"
>>> s2 = "orange is not delicious"

>>> from itertools import zip_longest
>>> "".join([c2 if (c1 == 'o' and c2) else c1 for c1, c2 in zip_longest(s1, s2, fillvalue='')])
'frad is delicidus'
1

The shortest solution i found:

a="food is delicious"
b="orange is not delicious"
''.join(y if x is 'o' else x for (x, y) in zip(a, b))
>>>> frad is delicidus

Note that the result string will have the length of the shorter of the two, because otherwise it would be undefined what to replace the remaining os with.

2
  • 3
    Don't use is to compare objects. Dec 7, 2016 at 6:51
  • Also, this will not work if the a is longer than b. Dec 7, 2016 at 6:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.