tags:

views:

214

answers:

5

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  A: 

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'
zweiterlinde
+2  A: 
s = "\n".join(['<li>' + i + '</li>' for i in x])
Robert Rossney
Is there an advantage to .join([...]) vs .join() in the previous example?
tester
Dancrew32 stole my comment - the square brackets are unnecessary here.
Triptych
'\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
zweiterlinde and I answered this question in the same minute. His/her answer's better.
Robert Rossney
@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.
John Fouhy
A: 

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.

fixermark
Thank you for your explanation.
tester
+1  A: 
list_output = "<li>%s</li>\n" * len(x) % tuple(x)
recursive
Clever, put possibly confusing. Not quite eligible for a downvote, but, this is a bit obscure.
S.Lott
I'd go with the join, but this one made me smile.
jlc
+2  A: 

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/"&gt;
          <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()
Alabaster Codify
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 =]
tester
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.
Alabaster Codify
your templating solution is longer and more complex. I don't see the benefit.
Seun Osewa
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.
mluebke
+1. Alabaster: don't worry, the best answers always get downvoted.
Ali A
Alabaster Codify
@mluebke: by "hand-coding HTML", I mean using Python to print HTML constructs. As stated, I wasn't answering the posted question, I was addressing the implied question: how can I create dynamic HTML based on user input.
Alabaster Codify
If a man doused in gasoline asked for your help in lighting some candles, would you lend him your lighter or tell him to avoid naked flames? We need to be helping the OP realise why the *approach* he's taking is flawed, not help him iron out the details of the implementation.
Alabaster Codify
+1: best way of generating html is by using a template engine
nosklo
What is the point of the make_link function?
John Fouhy
No point - I just included it so as to leave the input loop the same as OP's
Alabaster Codify