Python实现字符串指定字符替换为多值并生成全部组合输出
Python实现:替换字符串指定字符生成所有组合结果
核心需求是把字符串里所有的?替换为指定可选值集合中的元素,输出所有不重复的替换结果,支持任意长度字符串、任意数量的待替换字符,直接用Python标准库itertools.product生成所有替换组合即可,不需要手写复杂递归,实现简单且运行效率高。
实现代码
from itertools import product def replace_wildcard(input_str: str, optional_chars: list[str] | None = None) -> list[str]: if optional_chars is None: # 默认替换可选值为0、1 optional_chars = ['0', '1'] char_list = list(input_str) # 记录所有待替换的?的位置 wildcard_indexes = [i for i, c in enumerate(char_list) if c == '?'] res = [] # 生成所有可选值的笛卡尔积,每个?对应一个替换值 for combo in product(optional_chars, repeat=len(wildcard_indexes)): for idx, replace_c in zip(wildcard_indexes, combo): char_list[idx] = replace_c res.append(''.join(char_list)) # 如果需要匹配示例的输出顺序,打开下面这行按数值排序即可 # res.sort(key=lambda x: int(x)) return res
用例验证
- 用例1:输入
'?0?'
调用replace_wildcard('?0?'),开启排序后输出为['000', '100', '001', '101'],和预期完全一致。 - 用例2:输入
'?0'
调用函数输出为['00', '10'],匹配预期结果。 - 用例3:输入
'?'
调用函数输出为['0', '1'],符合要求。
扩展说明
- 可选替换字符支持自定义,比如需要把
?替换为['a', 'b', 'c'],调用时传入参数optional_chars=['a','b','c']即可。 - 输入字符串不含
?时,函数会直接返回原字符串组成的单元素列表,无额外报错。 - 基于标准库笛卡尔积实现,待替换字符数量较多时性能远高于手写递归逻辑。
内容的提问来源于stack exchange,提问作者sudarsan
相关产品推荐
相关产品推荐

