用括号逃脱的牙套格式化弦
我有一个字符串,其中包含牙套中的排列:
string = "3+3={3+3}"
我想找到所有的漏洞,并因表达式而替换它们(使用评估)。 我也想制作某种括号逃脱机制。 我可以自己做:
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
但是我关心它的工作速度,所以我想使用C函数。 我尝试使用re.finditer(r“ \ {\ w+\}”
)来做到这一点,但是我不知道,我该如何逃脱re。所以我需要这样的东西:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更快的方法:
在
import re
之后,定义一个字符串:查找括号中的所有参数:
求解方程:
最后替换字符串中的括号(
sub
)并使用结果格式化
字符串:Faster way to do this:
After
import re
, define a string:find all the arguments in the brackets:
solve the equations:
finally replace the brackets in the string (
sub
) andformat
the string with the results: