如何高效用列表元素依次替换字符串中的指定字符?
问题
现有字符串:
input_str = 'The substring of "python" from index @ to index @ inclusive is "tho"'
以及索引列表:
idx_list = [2, 4]
需要将input_str中的@字符依次替换为idx_list中的元素,得到输出:
output_str = 'The substring of "python" from index 2 to index 4 inclusive is "tho"'
我已编写如下代码实现:
def replace_char(input_str, idx_list): output_str = "" idx = 0 for i in range(0, len(input_str)): if input_str[i] == '@': output_str += str(idx_list[idx]) idx += 1 else: output_str += input_str[i] return output_str
请问是否存在比当前拼接方式更简洁高效的实现方法?
更简洁高效的实现方法
当然有,Python提供了多种更简洁且高效的字符串处理方式,下面列举几种常用方案:
1. 使用字符串format()方法
这是最直观且符合Python风格的写法,把@替换为占位符{}后,直接用列表元素填充:
def replace_char(input_str, idx_list): return input_str.replace('@', '{}').format(*idx_list)
先将所有@替换为format的标准占位符,再用*解包索引列表传入方法,自动按顺序填充占位符,代码极简且可读性拉满。
2. 使用split()+join()组合
通过@分割原字符串,再用索引列表的元素依次拼接片段:
def replace_char(input_str, idx_list): parts = input_str.split('@') return ''.join([p + str(v) for p, v in zip(parts, idx_list + [''])])
用@分割后得到的片段数量会比@的数量多1,给idx_list补一个空字符串,就能保证zip能匹配所有片段,最后用join一次性拼接结果——避免了循环中多次+=拼接的性能损耗(每次+=都会生成新字符串对象,而join是一次性完成拼接)。
3. 生成器表达式配合迭代器
逻辑和原循环类似,但用迭代器和生成器简化代码:
def replace_char(input_str, idx_list): it = iter(idx_list) return ''.join(str(next(it)) if c == '@' else c for c in input_str)
把索引列表转成迭代器,遍历原字符串每个字符,遇到@就取迭代器的下一个元素,否则保留原字符,最后用join生成最终字符串,比原循环的多次+=更高效。
性能说明
原代码循环中用output_str += ...,每次拼接都会创建新的字符串对象,当处理长字符串时性能会明显下降。上面三种方法都只生成最终的一个字符串对象,效率更高,同时代码更简洁易维护。
内容的提问来源于stack exchange,提问作者plpm
相关产品推荐
相关产品推荐

