Replacing or substituting in a python string does

2019-07-28 23:23发布

问题:

I could almost solve all of my python problems thanks to this great site, however, now I'm on a point where I need some more and specific help.

I have a string fetched from a database which looks like this:

u'\t\t\tcase <<<compute_type>>>:\n\t\t\t\t{\n\t\t\t\t\tif (curr_i <= 1) Messag...

the string is basically plain c code with unix line endings and supposed to be treated in a way that the values of some specific variables are replaced by something else gathered from a Qt UI.

I tried the following to do the replacing:

tmplt.replace(u"<<<compute_type>>>", str(led_coeffs.compute_type))

where 'led_coeffs' is a namedtuple and its value is an integer. I also tried this:

tmplt = Template(u'\t\t\tcase ${compute_type}:\n\t\t\t\t{\n\t\t\t\t\tif (curr_i <= 1) Messag...)
tmplt.substitute(compute_type = str(led_coeffs.compute_type))

however, both approaches do not work and I have no idea why. Finally I was hoping to get some input here. Maybe the whole approach is not right and any hint on how to achieve the replacing in a good manner is highly appreciated.

Thanks, Ben

回答1:

str.replace (and other string methods) don't work in-place (string in Python are immutable) - it returns a new string - you will need to assign the result back to the original name for the changes to take effect:

tmplt = tmplt.replace(u"<<<compute_type>>>", str(led_coeffs.compute_type))

You could also invent your own kind of templating:

import re
print re.sub('<<<(.*?)>>>', lambda L, nt=led_coeffs: str(getattr(nt, L.group(1))), your_string)

to automatically lookup attributes on your namedtuple...