tags:

views:

64

answers:

3

I got a bot from this website, and I've been having a lot of fun with it. However I wanted to add an away command. The way it's gonna work is that when someone write

 away [reason]

then it saves the reason, and when someone else types his name, the bot sais "He is not available, he left a note '[reason]'" or something like that. The input I get when someone writes to the bot is

 :[email protected]
 PRIVMSG #mychat :away Im going
 fishing.

Using this

 line[0][line[0].index(":")+1:line[0].index("!")]

I got the username of the person (in this case, it's NickName), and I need to extract all lines after away, using line[4:] (Im going fishing), and that works like a charm. But I need to make it into a string, because it can't return a string and a list.

tl;dr I get a list as a value, and I want it to return it with a string, what do I do?

A: 

If you want to turn a list into a string just use 'x'.join(mylist), where x is the character you want between each element (such as a space, comma, etc.), then you can just concatenate that with your other string.

I though I guess there are two different ways, but I'm not sure which is faster (or if you'll be doing it enough to make a difference)

...
mylist.append(mystr)
return ' '.join(mylist)

and

...
return ' '.join(mylist) + ' ' + mystr

though I think the former way looks better.

edit:
If your list contains non-strings you can feed a generator expression to .join():

return ' '.join(str(_) for _ in mylist)
Wayne Werner
A: 

If it is a list of strings you can just do:

''.join(stringlist)

which concatenates all the strings, making it one string.

See str.join()

Felix Kling
Thanks a lot, worked perfectly ;)
Pappegye
+1  A: 

You can do what you want like this:

line = [
    ':[email protected]',
    'PRIVMSG #mychat :away Im going',
    'fishing.'
]

away = '\n'.join(line[1:])
needle = ':away '
away = away[away.index(needle) + len(needle):]
print away

Result:

Im going
fishing.

If you want the output on one line use ' '.join(line[1:]) instead of '\n'.join(line[1:]).

Mark Byers