I am using the code below to find any words enclosed by "<<" and ">>" in a string and replace them with the relevant previously defined variable. This works, but is there a safer or more efficient way to accomplish this? I have seen several warnings about the use of eval, and my solution seems overly complicated.
import re
aa = 'alpha'
bb = 'beta'
cc = 'gamma'
teststr = 'A for <<aa>>, b means <<bb>>, and c could be <<cc>>.'
matches = re.finditer('<<(\w*)>>', teststr)
for i in matches:
teststr = teststr.replace(i.group(0), eval(i.group(1)) )
print teststr