Python conditional replace

Viewed 60

I need conditional replace in string.

input_str = "a111a11b111b22"

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

output_str = "a111a11Z11122"

maybe I need to use [0] and [-1] for remove "b"s and "Z"+any number

but I can't find conditional replace for it.

2 Answers

Try with regex:

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

You should use regular expressions. They are really useful:

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

# output_str is "a111a11Z11122"

The r'b(\d+)b' regexpr matches letter b, followed by 1 or more digits and other letter b. The parenthesis memorizes the digits for further use (with \1) in the replacement part of the sentence (letter Z and \1).

Related