使用列表推导和zip方法实现子字符串的替换。
示例代码如下:
str1 = "abcde"
str2 = "xyz"
replace_indices = [1, 3]
str1 = "".join([str2 if i in replace_indices else ch for i, ch in zip(range(len(str1)), str1)])
print(str1) # 输出 "axyze"
这里的关键是使用列表推导和zip方法将字符串和索引一起遍历,然后根据索引序列直接对字符串中需要替换的位置进行子字符串的替换。