views:

329

answers:

4

Say I have the following string:

"I am the most foo h4ck3r ever!!"

I'm trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element, resulting in:

"I am the most <span class="special">foo></span> h4ck3r ever!!"

BeautifulSoup seemed like the way to go, but I haven't been able to make it work.

I could also pass this to the browser and do it with javascript, but that doesn't seem like a great idea.

Some advice for this would be really useful, especially in python.

+2  A: 

How about this:

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!!'
>>>
fuentesjr
I agree with this, though depending on the context, some error handling may be useful
daniel
+1  A: 

As far as I can tell, you're doing a simple string replace. You're replacing "foo" with "bar foo bar." So from string you could just use

replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

So for you it would be:

myStr.replace("foo", "<span>foo</span>")
Swati
A: 

If you wanted to do it with javascript/jQuery, take a look at this question: http://stackoverflow.com/questions/119441/highlight-a-word-with-jquery

nickf
A: 

Awesome. Thanks for the quick responses.

jamtoday