Python 条件替换

Python conditional replace

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

input_str = "a111a11b111b22"

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

output_str = "a111a11Z11122"

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

但我找不到条件替换它。

尝试使用正则表达式:

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

你应该使用 regular expressions。它们真的很有用:

import re
input_str = "a111a11b111b22"
output_str = re.sub(r'b(\d+)b', r'Z', input_str) 

# output_str is "a111a11Z11122"

r'b(\d+)b' 正则表达式匹配字母 b,后跟 1 个或多个数字和其他字母 b。括号记住数字,以便在句子的替换部分(字母 Z</code>)中进一步使用(使用 <code>)。