moemous
moemous

Reputation: 189

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

Hi this is my code for Telegram bot,I have a list that fills by names. the bot add usernames to list and reply it as a list I want to reply every name in seperate lines

list = []
txt = str(list)


def msg_filter(bot , update):
wordsp = ["man"," miam"]
wordsn = ['nemiam','nistam','na']

if len(list) <=15:

    if any (i in update.message.text for i in wordsp):

        if "{}".format(update.message.from_user.first_name) not in list:
            list.append("{}".format(update.message.from_user.first_name))
            bot.send_message(chat_id = update.message.chat_id , text = "{}".format(list))

I have this in output : ['username1','username2','username3']

but expect this:

[username
usernam2
username3]

Upvotes: 3

Views: 3329

Answers (4)

Viktoriia Kachanovska
Viktoriia Kachanovska

Reputation: 125

If you need exact this result without any quotes:

    [username1
    usernam2
    username3]

Try this simple solution:

    print(f'[{list_[0]}')
    for l in list_[1:-2]:
        print(l)
    print(f'{list_[-1]}]')

where list_ = ['username1','username2','username3']

Upvotes: 1

kederrac
kederrac

Reputation: 17322

you could use:

 print('\n'.join(list))
 # please do not name your list "list", list is a build-in function !!!

Upvotes: 2

Turtlefight
Turtlefight

Reputation: 10680

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)

Upvotes: 1

DisplayName
DisplayName

Reputation: 87

text="[{}]".format("\n".join(lst))

Upvotes: 1

Related Questions