Python条件替换

2024-09-30 16:34:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要字符串中的条件替换

input_str = "a111a11b111b22"

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

output_str = "a111a11Z11122"

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

但我找不到它的条件替换


Tags: to字符串numberinputoutputany数字condition
2条回答

您应该使用regular expressions。它们非常有用:

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

# output_str is "a111a11Z11122"

r'b(\d+)b'regexpr与字母b匹配,后跟1个或多个数字和其他字母b。括号存储句子替换部分(字母Z\1)中的数字以供进一步使用

尝试使用正则表达式:

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

相关问题 更多 >