'Outputting HTML unordered list python
I'm attempting to write a function with python that will take an list of strings that I have defined and display them as a single string that is and HTML unordered list of said strings. So far my code is:
def pizzatoppings(self):
toppings = ['mushrooms', 'peppers', 'pepparoni', 'steak', 'walnuts', 'goat cheese', 'eggplant', 'garlic sauce'];
for s in toppings:
ul += "<li>"+str(s)+"</li>"
ul += "</ul>"
return ul
When I attempt to run this however I get no traceback and nothing happens. Does anyone know why this is happening? I know this is probably a trivial question but I've searched for answers and cannot find a solution. Thanks!
Solution 1:[1]
Looks like you are trying to build a website. Why don't you use a template engine, like Jinja 2 for this, instead of printing a HTML snippet from a function? For that you will need a Python web application, plausibly written in one of web frameworks. I'd go for Flask here, it's simple to start working with and Jinja is a default template engine for Flask.
If you just want to generate static HTML files, I would recommend Frozen-Flask, which allows you to generate static HTML files that can be hosted without a need to deploy any Python web application on your server. Just copy generated files to your hosting and you are ready to go.
If you still want to just print a HTML snippet, your code should be something like Ealhad posted in his answer.
Also, you original code contains a few problems:
def pizzatoppings(self):
# you don't need semicolons in Python
toppings = ['mushrooms', 'peppers', 'pepparoni', 'steak', 'walnuts', 'goat cheese', 'eggplant', 'garlic sauce']
# you need to initialize a "ul" variable
ul = "<ul>"
for s in toppings:
ul += "<li>"+str(s)+"</li>"
# following two lines where indented too much. In Python, indentation defines a block of code
ul += "</ul>"
return ul
Solution 2:[2]
I was just doing this at work today. Here's my two-line solution:
def example(elements):
return '<ul>\n' + '\n'.join(['<li>'.rjust(8) + name + '</li>' for name in elements]) + '\n</ul>'
Which gives:
<ul>
<li>mushrooms</li>
<li>peppers</li>
<li>pepparoni</li>
<li>steak</li>
<li>walnuts</li>
<li>goat cheese</li>
<li>eggplant</li>
<li>garlic sauce</li>
</ul
This makes the generated HTML code a little easier to read.
Solution 3:[3]
I tried this instead and it was a little simpler for me
for item in items:
html_str += "<li>" + str(item) + "</li>\n"
html_str += "</ul>"
print(html_str)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | glu |
| Solution 2 | Mike Woodward |
| Solution 3 | Vern |
