如何优雅地将一个字符串中特定位置的字符替换为另一个字符串中相同位置的字符?

3
我希望用一个字符串中的每个字符替换另一个字符串中相同索引处的字符。如果该索引处没有字符,则保留原样。
以下是我使用列表推导式(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)

结果

frad is delicidus

不过感觉应该有更好的方法,比如使用 str.replace。有什么想法吗?

2个回答

2
你可以使用 itertools.zip_longest 来迭代两个字符串,直到它们中更长的那一个用尽为止。较短的字符串将被填充上 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
我找到的最短解决方案是:
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

请注意,结果字符串的长度将是两者中较短的那一个,否则替换剩余的o将是未定义的。

3
不要使用“is”来比较对象。 - thefourtheye
此外,如果 ab 更长,则这将无法工作。 - thefourtheye

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接