假设我有以下字符串:
"I am the most foo h4ck3r ever!!"
我正在尝试编写一个 makeSpecial(foo) 函数,其中 foo 子字符串将包装在新的 span 元素中,结果是:
"I am the most <span class="special">foo></span> h4ck3r ever!!"
BeautifulSoup 似乎是可行的方法,但我一直无法使其发挥作用。
我也可以将其传递给浏览器并使用 JavaScript 来完成,但这似乎不是一个好主意。
对此的一些建议非常有用,尤其是在 python 中。
最佳答案
这个怎么样:
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def makeSpecial(mystring, special_substr):
... return mystring.replace(special_substr, '<span class="special">%s</span>
' % special_substr)
...
>>> makeSpecial("I am the most foo h4ck3r ever!!", "foo")
'I am the most <span class="special">foo</span> h4ck3r ever!!'
>>>
关于javascript - 向文本子字符串添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/125102/