The following python code does work but the regular expression 'search' is evaluated twice:
# my_string varies, it gets the following strings = ['%10s', 'comma%11d', 'comma%-6.2f', '%-8s'] in a loop
output_string = '|'
re_compiled_pat_int = re.compile(r'comma%(d+)d')
re_compiled_pat_fp = re.compile(r'comma%-?(d+).(d+)f')
re_compiled_pat_str = re.compile(r'%(-?d+)s')
if re_compiled_pat_int.search(my_string):
output_string += f' %s{re_compiled_pat_int.search (my_string).group(1)}s |' # results in | %10s |"
elif re_compiled_pat_fp.search(fld_format):
output_string += f' %-{re_compiled_pat_fp.search(my_string).group(1)}s |'
elif re_compiled_pat_str.search(my_string):
output_string += f' %{re_compiled_pat_str.search(my_string).group(1)}s |'
# 'output_string' becomes: '| %10s | %-11s | %-6s | %-8s |'
As you can see, for each if/elif I need the capture group string to be also plugged into the output string, but I see no way but to re-evaluate it in order to extract the captured group. As noted here, python 3.8'th Walrus operator (:=) can be used but I still have Python 3.6.
Is there a more elegant way to use the evaluated group just once?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…