0

In this loop, I'm trying to take user input and continually put it in a list till they write "stop". When the loop is broken, the for loop prints out all of the li's.

How would I take the output of the for loop and make it a string so that I can load it into a variable?

x = ([])
while True:
    item = raw_input('Enter List Text (e.g. <li><a href="#">LIST TEXT</a></li>) (Enter "stop" to end loop):\n')
    if item == 'stop':
        print 'Loop Stopped.'
        break           
    else:
        item = make_link(item)
        x.append(item)
        print 'List Item Added\n'


    for i in range(len(x)):
        print '<li>' + x[i] + '</li>\n'

I want it to end up like this:

Code:

print list_output

Output:

<li>Blah</li>
<li>Blah</li>
<li>etc.</li>
2
  • What do you want to do if someone enters '</li>'? It should be escaped for use in the web, which means using 'cgi.escape'. There's also possible problems with how web browsers figure out the character encoding. It's really best to use a templating system for ll but a restricted number of cases. Commented Feb 25, 2009 at 13:06
  • There is a bug in your code: the for-loop should not be indented! Commented Feb 25, 2009 at 20:52

6 Answers 6

3

In python, strings support a join method (conceptually the opposite of split) that allows you to join elements of a list (technically, of an iterable) together using the string. One very common use case is ', '.join(<list>) to copy the elements of the list into a comma separated string.

In your case, you probably want something like this:

list_output = ''.join('<li>' + item + '</li>\n' for item in x)

If you want the elements of the list separated by newlines, but no newline at the end of the string, you can do this:

list_output = '\n'.join('<li>' + item + '</li>' for item in x)

If you want to get really crazy, this might be the most efficient (although I don't recommend it):

list_output = '<li>' + '</li>\n<li>'.join(item for item in x) + '</li>\n'
Sign up to request clarification or add additional context in comments.

Comments

2
s = "\n".join(['<li>' + i + '</li>' for i in x])

5 Comments

Is there an advantage to .join([...]) vs .join() in the previous example?
Dancrew32 stole my comment - the square brackets are unnecessary here.
'\n'.join will not add a '\n' at the end of the generated string, which is why I didn't use this form. If you want one, follow my example :)
zweiterlinde and I answered this question in the same minute. His/her answer's better.
@Dancrew32: Leaving out the [] is more pythonic these days. [] means "create a list, then run join on it". leaving them out gives you a generator instead, which avoids creating the list and just gives you the next element when you ask for it. A bit like range vs xrange in python 2.x.
2

I hate to be the person to answer a different question, but hand-coded HTML generation makes me feel ill. Even if you're doing nothing more than this super-simple list generation, I'd strongly recommend looking at a templating language like Genshi.

A Genshi version of your program (a little longer, but way, way nicer):

from genshi.template import MarkupTemplate

TMPL = '''<html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:py="http://genshi.edgewall.org/">
          <li py:for="item in items">$item</li>
          </html>'''

make_link = lambda x: x

item, x = None, []
while True:
    item = raw_input('Enter List Text (Enter "stop" to end loop):\n')
    if item == 'stop':
        break
    x.append(make_link(item))
    print 'List Item Added\n'

template = MarkupTemplate(TMPL)
stream = template.generate(items = x)
print stream.render()

10 Comments

I appreciate the recommendation, however the chunk of code I posted here is a very small piece of something else geared toward making layouts. It's a learning process for me still =]
OK, in that case I can only recommend templating more strongly: for larger layouts they pay off even more. I appreciate you're learning the language, but hand-coding HTML generation is just teaching you bad habits, especially in Python.
your templating solution is longer and more complex. I don't see the benefit.
The question "How do I join a list into a string" is answered with "use xhtml templates!". Ugh. Also you are saying don't use hand coded html, but here use this hand coded html.
+1. Alabaster: don't worry, the best answers always get downvoted.
|
1
list_output = "<li>%s</li>\n" * len(x) % tuple(x)

2 Comments

Clever, put possibly confusing. Not quite eligible for a downvote, but, this is a bit obscure.
I'd go with the join, but this one made me smile.
1

Maybe because everyone here is a professional python-er, but it would have been nice to get an answer that addressed the OP's format. I came here because I had a similar question in a similar context. I finally found the solution, and I am not sure why the answers above would be considered preferable.

Using OP's code: (which I can't totally test because I don't have "raw_input" or "make_link" function defined):

x = ''

while True:
    item = raw_input('Enter List Text (e.g. <li><a href="#">LIST TEXT</a></li>) (Enter "stop" to end loop):\n')
    if item == 'stop':
        print 'Loop Stopped.'
        break           
    else:
        item = make_link(item)
        x = x + '<li>' + item + '</li>\n'
        print 'List Item Added\n'

So the differences are that we have defined the variable x as an empty string as opposed to an empty list, and we've replaced the for loop with iterations of the else (however many times user inputs a non-'stop' value for the variable item).

Comments

0

Replace your for loop at the bottom with the following:

list_output=""
for aLine in x:
    list_output += '<li>'+aLine+'</li>\n'

Note also that since x is a list, Python lets you iterate through the elements of the list instead of having to iterate on an index variable that is then used to lookup elements in the list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.