如何重复替换二进制字符串中所有"00000"为"0"?含正则方案
二进制字符串重复替换
00000为0的解决方案 现有代码问题分析
你的代码逻辑存在多处错误,导致无法实现需求:
- 使用
split("00000")拆分后,列表中不会存在"00000"元素,因此if i == "00000"永远不会触发。 l.index(i-3)是错误写法:i是字符串类型,不能直接与数字做减法,会触发类型错误。del l[i-y]逻辑错误:i是列表元素而非索引,无法用于删除列表元素。- 整体仅做了一次拆分拼接,没有实现反复替换直到无连续5个0的核心需求。
方案一:非正则(栈实现)
通过栈跟踪连续0的数量,遍历过程中实时处理替换规则,直到无法再替换:
def replace_five_zeros(s): stack = [] zero_count = 0 for char in s: if char == '0': zero_count += 1 else: # 处理累计的0,反复替换到数量小于5 while zero_count >= 5: zero_count = zero_count // 5 + zero_count % 5 stack.append('0' * zero_count) stack.append(char) zero_count = 0 # 处理遍历结束后剩余的0 while zero_count >= 5: zero_count = zero_count // 5 + zero_count % 5 stack.append('0' * zero_count) return ''.join(stack) # 测试示例 print(replace_five_zeros('0'*25)) # 输出: '0' print(replace_five_zeros('0'*50)) # 输出: '00' print(replace_five_zeros('0'*125)) # 输出: '0' print(replace_five_zeros('0000010000000000')) # 输出: '010'
方案二:正则表达式(一次性计算最终结果)
利用正则匹配所有连续0串,通过回调函数直接计算该串最终应替换的0数量,无需多次替换:
import re def calculate_final_zeros(match): zero_len = len(match.group()) # 反复计算直到0的数量小于5 while zero_len >= 5: zero_len = zero_len // 5 + zero_len % 5 return '0' * zero_len def replace_five_zeros_regex(s): # 匹配任意连续的0序列 return re.sub(r'0+', calculate_final_zeros, s) # 测试示例 print(replace_five_zeros_regex('0'*25)) # 输出: '0' print(replace_five_zeros_regex('0'*50)) # 输出: '00' print(replace_five_zeros_regex('0'*125)) # 输出: '0' print(replace_five_zeros_regex('0000010000000000')) # 输出: '010'
内容的提问来源于stack exchange,提问作者mac
相关产品推荐
相关产品推荐

