向文本子字符串添加新元素
时间:2020-03-06 14:38:21 来源:igfitidea点击:
说我有以下字符串:
"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!!' >>>
据我所知,我们正在执行一个简单的字符串替换。我们将" foo"替换为" bar foo bar"。因此,我们可以从字符串中使用
replace(old, new[, count])
返回该字符串的副本,其中所有出现的子字符串old都被new替换。如果给出了可选的参数count,则仅替换第一个出现的计数。
因此,对我们而言,它将是:
myStr.replace("foo", "<span>foo</span>")
如果我们想使用javascript / jQuery,请看一下这个问题:使用jQuery突出显示一个单词