Welcome, guest | Sign In | My Account | Store | Cart

This function simply takes a single-dimension sequence and converts into into an HTML unordered list. This function makes it simple to present the contents of a sequence on the web in an neat fashion.

Python, 10 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def SequenceToUnorderedList(seq):

	html_code = "<ul>" + "\n\n"

	for item in seq:
		html_code = html_code + "<li>" + item + "\n"

	html_code = html_code + "\n" + "</ul>" 

	return html_code

Data (whether retrived from a file, database, etc) is usually retrived into a sequence. This function provides a quick way to present this information. I only made this function for one-dimensional sequences, because there would be no uniform way to do multi-dimensional sequences. If I were to make this function for multi-dimensional sequences, it would be unportable and wouldn't scale to every project..

3 comments

Hamish Lawson 20 years, 5 months ago  # | flag

Handle multidimensional lists using recursion. The function could handle multidimensional lists if recursion were used:

def SequenceToUnorderedList(seq):
    html_code = "&lt;ul>\n"
    for item in seq:
        if type(item) == type([]):
            html_code += SequenceToUnorderedList(item)
        else:
            html_code += "&lt;li>%s&lt;/li>\n" % item
    html_code += "&lt;/ul>\n"
    return html_code
Tracy Ruggles 20 years, 5 months ago  # | flag

Recursion w/ indentation. You could also have it nicely format your recursion:

def SequenceToUnorderedList(seq,i=1):
    tab = '\t'
    html_code = "%s\n" % (tab*(i-1))
    for item in seq:
        if type(item) == type([]):
            html_code += SequenceToUnorderedList(item, i+1)
        else:
            html_code += "%s%s\n" % (tab*i, item)
    html_code += "%s\n" % (tab*(i-1))
    return html_code
Scott David Daniels 20 years, 1 month ago  # | flag

List Comprehensions are a natural here. A list comprehension may make the body clearer:

def SequenceToUnorderedList(seq):
    return "\n".join(["&ltul>\n"] +
               ["&ltli> " + item for item in seq] +
               ["\n&lt;/ul>\n"])
Created by Mark Nenadov on Tue, 19 Jun 2001 (PSF)
Python recipes (4591)
Mark Nenadov's recipes (12)

Required Modules

  • (none specified)

Other Information and Tasks