替换或替换 python 字符串不起作用
感谢这个伟大的网站,我几乎可以解决我所有的 Python 问题,但是,现在我需要更多和具体的帮助.
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...
该字符串基本上是带有 unix 行结尾的纯 c 代码,并且应该以某种方式处理某些特定变量的值,以将某些特定变量的值替换为从 Qt UI 收集的其他内容.
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))
其中 'led_coeffs' 是一个命名元组,它的值是一个整数.我也试过这个:
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.
谢谢,本
str.replace
(和其他字符串方法)不能就地工作(Python 中的字符串是不可变的) - 它返回一个新字符串 - 您需要将结果分配回原始名称以使更改生效:
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...