Python: How to Print Separate Lines from a List

how can I split a list and print it in separate lines?

If you want to output the list new-line separated you can use #join and use the newline-character (\n) as separator for your list entries.

For example:

bot.send_message(chat_id = update.message.chat_id , text = "\n".join(list))

which will output:

username1
username2
username3

If you explicitly want the [ & ] outputed as well, you can use format to add them:

text = "[\n{}\n]".format("\n".join(list))
bot.send_message(chat_id = update.message.chat_id , text = text)

Python Print list on separate lines

cursor.execute('SELECT username, score FROM Players order by score DESC limit 5')
topscore = cursor.fetchall()

topscore = list(topscore)
for i in topscore:
print(i[0],i[1],sep=' , ')
print('\n')

Least line code to print a list of tuple in separate line

Seems much nicer to use tuple unpacking here:

s=[('c',2),('a',2),('b',3)]

for x, y in s:
print(x, y)

Or this:

for x in s:
print(*x)

Output:

c 2
a 2
b 3

Have a look at Unpacking Argument Lists from the documentation as to why the above works.

How can my function print out lines of "#". The argument is a list of integers and they specify how many "#" each line should contain

Your list_of_char() func returns a list, which you then print out. So you're seeing exactly what you're asking for.

If you want to print out strings, you need to either create the string in list_of_char() and return the string instead of a list. Or, you can take the returned list and print the elements of that list one at a time. Or you can convert the list of strings into a single string and print that out.

In the func you could change:

return my_new_list

to:

return '\n'.join(my_new_list)

which then would have the func return a single string.

In the alternative, you could change "main" from:

print(list_of_char([2,3]))

to:

print('\n'.join(list_of_char([2,3])))

Or, you could handle the list items one at a time (which now means not adding the extra newline (because you'll get one by default from print():

for line in list_of_char([2,3]):
print(line)


Related Topics



Leave a reply



Submit