1

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 Answer 1

0

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...

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. What a stupid mistake. Thanks also for the templating example. I'll test it asap.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.