Reputation: 802
I have the following string:
{At condition {0}, the value of {1} must be between {2} and {3}.}{{code{min <= 100}}}{{code{min}}}{0}{100}
How to convert any similar string to the below format in python?
At condition `min <= 100`, the value of `min` must be between 0 and 100.
Numbers in curly brackets should be replaced by the corresponding values. If a value is wrapped into {code{value}}
, dedicated symbols `` should be added.
Upvotes: 0
Views: 473
Reputation: 879
Alright this is a little brittle/messy but it should work given the structure you provided.
def convert(s):
# Find index of first }{ as this is end of initial string
idx = s.find('}{')
initial = s[1:idx]
# Everything after this index is an argument
args = s[idx+2:-1]
args = args.split('}{')
# Iterate through args and subsitute into initial string
for i, arg in enumerate(args):
# Check to see if arg wrapped in {code{}}
val_idx = arg.find('code{')
if val_idx != -1:
# Replace wrapped value with backticks
arg = '`{}`'.format(arg[val_idx+5:-2])
# Place arg into proper place in initial string
initial = initial.replace('{{{}}}'.format(i), arg)
return initial
Calling:
convert('{At condition {0}, the value of {1} must be between {2} and {3}.}{{code{min <= 100}}}{{code{min}}}{0}{100}')
convert('{{0} bar}{foo}')
Returns:
At condition `min <= 100`, the value of `min` must be between 0 and 100.
foo bar
Upvotes: 1