#!/usr/bin/env python
# stringbuild.py -- shows how to build a string efficiently

def ul_inefficient(list_of_items):
    "Create and return a <ul> list of <li> items as string."
    s = '<ul>'
    for item in list_of_items:
        s = s + '\n<li>%s</li>' % escape_html(item)
    s = s + '\n</ul>'
    return s

def ul_efficient(list_of_items):
    "Create and return a <ul> list of <li> items as string."
    slist = ['<ul>']
    for item in list_of_items:
        slist.append('<li>%s</li>' % escape_html(item))
    slist.append('</ul>')
    return '\n'.join(slist)

def escape_html(s):
    '''Escape HTML special characters.

    Given a string s, escape the HTML special characters
    "&", "<" and ">". Return the escaped string.'''

    return s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')

if __name__ == '__main__':
    thelist = [ 'Python', 'Ruby', 'Perl', 'PHP' ]
    ul_string1 = ul_inefficient(thelist)
    ul_string2 = ul_efficient(thelist)
    assert ul_string1 == ul_string2
