首页 > 解决方案 > Python 条件替换

问题描述

我需要在字符串中进行条件替换。

input_str = "a111a11b111b22"

condition : ("b" + any number + "b") to ("Z" + any number)

output_str = "a111a11Z11122"

也许我需要使用 [0]and[-1]删除“b”和“Z”+任何数字

但我找不到它的条件替换。

标签: pythonpython-3.xreplaceregular-language

解决方案


尝试使用正则表达式:

import re
input_str = "a111a11b111b22"
output_str = re.sub(r'[b](\d)',r'Z\1',input_str)
print(output_str)

推荐阅读