所以,假设我有一个这样的字符串:
a = "√22+34-4+√(2+3)/5+√3"
注意:字符串a是用户输入,每次都可以更改。
我想管理字符串是这样的:
a = "√(22)+34-4+√(2+3)/5+√(3)"
然后我可以使用a.replace("√","sqrt").
有什么建议吗?抱歉我的英语不好:) 感谢
答案 0 :(得分:4)
您可以尝试re.sub()
:
>>> import re
>>> a = "√22+34-4+√(2+3)/5+√3"
>>> re.sub(r'√(\d+)', r'√(\1)', a) # \1 is whatever was captured by (\d+)
'√(22)+34-4+√(2+3)/5+√(3)'
但如果你需要更复杂的东西,你可能不得不编写某种解析器。