1

I'm creating a chat bot for twitch, more importantly, I'm attempting to have a list that can be added to during iteration and can also be accessed to from within the channel chat. This is the overall code:
https://pastebin.com/maCbceaB
I'm focused on this portion of the code however:

clist = ["!add", ]
        if message.strip() == "!add":
            chat(s, "Syntax: !add !<command> <what the command does>")
        if message.strip().startswith("!add"):
            clist.append(message[5:])
            chat(s, "The command has been added!")

EDIT: I'm moreso focused on how to add to the list while the code is iterating because I have to be able to add to the clist because it will be used in:

if message.strip() == "!commands":
            chat(s, clist)

Currently this code will only output: ['!add'] when !commands is used
All the options I've researched are typically for massive lists and mine will be consisted mostly of strings so I need something fairly simple.

  • 1
    Possible duplicate of [Checking whether a string starts with XXXX](https://stackoverflow.com/questions/8802860/checking-whether-a-string-starts-with-xxxx) – Kevin M Granger Aug 23 '17 at 22:53

1 Answers1

1

If you want to check if a string starts with a substring you can use the String startswith method:

if message.startswith('!add'):

and then you can grab the command by removing the '!add ' part using a String slice:

message[5:]

Your code will be as follows:

>>> clist = []
>>> message = '!add testcommand'
>>> if message.startswith('!add'):
>>>     clist.append(message[5:])
>>> clist
>>> ['testcommand']
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
  • 2
    I would suggest using `message[5:]`, rather than `message.replace('!add ', '')`. It may lose some clarity, but will also not lead to any unexpected results if `!add` appears later in the string, and is probably a little faster as it's more specified, and is more concise. – Izaak van Dongen Aug 23 '17 at 22:50
  • Replacing the substring means `'!add '` can't be part of your list. You could use `message[len('!add '):]` instead to capture everything after the first `'!add '` – codehearts Aug 23 '17 at 22:50
  • The add command would have to be a hardcoded value anyways, because you couldnt add it to the clist by doing '!add !add'.. – Alan Kavanagh Aug 23 '17 at 22:54