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>
In python, strings support a
joinmethod (conceptually the opposite ofsplit) 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:
If you want the elements of the list separated by newlines, but no newline at the end of the string, you can do this:
If you want to get really crazy, this might be the most efficient (although I don’t recommend it):