I need to change "{{" & "}}" to "{" & "}", while at the same time also replacing "{" &"}" with "{{" & "}}".
Whichever way round I do this, one replacement will always interfere with the other. At the moment my best solution is to use replace with intermediate delimiters. However it feels like there should be a better/quicker solution.
I looked at str.translate(), but that is for single character replacements only. Any suggestions of an alternative way of doing this?
Also whatever I use as intermediate delimiters could potentially interfere with the incoming HTML if they happen to be contained within that (unless anyone can suggest any delimiters which could be used in Python but would be illegal in HTML/JavaScript).
Also tried a couple of different regex methods but they are both four times slower than .replace(). See my test code below:
import re
import datetime
x = "here is {javascript}, but here is a pythonExpression {{var1}}"
print("1 begin:", x)
start = datetime.datetime.now()
for _ in range(1000001):
x = x.replace("{{", "<<").replace("}}", ">>")
x = x.replace("{", "{{").replace("}", "}}")
x = x.replace("<<", "{").replace(">>", "}")
finish = datetime.datetime.now()
print("1 end:", x) # -> here is {{javascript}}, but here is a pythonExpression {var1}, hmm how to deal with that.
print("Runtime (1000001): ", finish-start) # <- 3.7s
x = "here is {javascript}, but here is a pythonExpression {{var1}}"
print("2 begin:", x)
d = {"{{": "{", "}}": "}", "{": "{{", "}": "}}"}
start = datetime.datetime.now()
for _ in range(1000001):
x = re.sub("|".join(d), lambda x: d[x.group(0)], x)
finish = datetime.datetime.now()
print("2 end:", x) # -> here is {{javascript}}, but here is a pythonExpression {var1}, hmm how to deal with that.
print("Runtime (1000001): ", finish-start) # <- 13s
def replacer(val):
match val.group(0):
case "{{":
return "{"
case "}}":
return "}"
case "{":
return "{{"
case "}":
return "}}"
return ""
x = "here is {javascript}, but here is a pythonExpression {{var1}}"
print("3 begin:", x)
# x = re.sub("'{{' '}}' | '{' | '}'", myfunc(), x)
start = datetime.datetime.now()
for _ in range(1000001):
x = re.sub("({{|}}|{|})", replacer, x, flags=re.MULTILINE)
finish = datetime.datetime.now()
print("3 end:", x) # -> here is {{javascript}}, but here is a pythonExpression {var1}, hmm how to deal with that.
print("Runtime (1000001): ", finish-start) # <- 12.5s