'Formatting string by braces with braces escaping
I have a string, that contains expresions in braces:
string = "3+3={3+3}"
I want to find all expresions and replace them by result of expression (using eval). Also I want to make some kind of braces escaping mechanism. I can do it by myself:
final = ""
opened_eval = False
short_escaping = False
long_escaping = False
inner_string = ""
for letter in string:
if opened_eval:
if letter == "}":
final += eval(inner_string, kwargs)
inner_string = ""
opened_eval = False
else:
inner_string+=letter
elif short_escaping:
opened+=letter
short_escaping=False
elif long_escaping:
if letter == "|":
long_escaping=False
else:
opened+=letter
else:
if letter == "\\":
short_escaping=True
elif letter == "|":
long_escaping=True
elif letter=="{":
opened_eval = True
else:
final+=letter
>>> print(final)
3+3=6
But I care about, how quickly does it work, so I want to use C function.
I tryed to do that with re.finditer (r"\{\w+\}"), but I don't know, how can I make escaping with re. So I need something like this:
for expression in find(r"a = {get_a()} \{text in braces\} b = {get_b()}"):
print(expression.text, expression.start, expression.end)
{get_a()} 5 13
{get_b()} 38 46
Solution 1:[1]
Faster way to do this:
After import re, define a string:
string = "3+3={3+3}, 7:4={7/4}, etc.."
find all the arguments in the brackets:
equations = re.findall("\{[^\{\}]*\}", string)
>>>['{3+3}', '{7/4}']
solve the equations:
results = [list(eval(equation))[0] for equation in equations]
>>>[6, 1.75]
finally replace the brackets in the string (sub) and format the string with the results:
re.sub("\{[^\{\}]*\}","{}",string).format(*results)
>>>'3+3=6, 7:4=1.75, etc..'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Salvatore Daniele Bianco |
