python - 如何在代码迭代时追加到列表并保存列表(对于 twitch 聊天机器人)

标签 python python-3.x list twitch

我正在为 twitch 创建一个聊天机器人,更重要的是,我正在尝试创建一个可以在迭代期间添加到其中并且也可以从 channel 聊天中访问的列表。这是整体代码:
https://pastebin.com/maCbceaB
不过,我关注的是这部分代码:

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!")

编辑:我更关注如何在代码迭代时添加到列表,因为我必须能够添加到 clist 因为它将用于:

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

目前,当使用 !commands 时,此代码只会输出:['!add']
我研究过的所有选项通常都是针对大量列表的,而我的选项主要由字符串组成,所以我需要一些相当简单的东西。

最佳答案

如果要检查字符串是否以子字符串开头,可以使用 String startswith 方法:

if message.startswith('!add'):

然后您可以通过使用字符串切片删除“!add”部分来获取命令:

message[5:]

您的代码如下:

>>> clist = []
>>> message = '!add testcommand'
>>> if message.startswith('!add'):
>>>     clist.append(message[5:])
>>> clist
>>> ['testcommand']

关于python - 如何在代码迭代时追加到列表并保存列表(对于 twitch 聊天机器人),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45850244/

相关文章:

list - 如何根据列表中的先前值过滤Haskell中的列表元素?

python - 如何使用 matplotlib.animation 从动态增长的列表中连续流式传输数据点以进行实时绘图?

python - 查找列表的所有可能子列表

python - 如何使用 pysimplesoap 构造 SOAP 消息?

python - 如何将多迹线图制作为可重用代码?

python - 重新绑定(bind)引发异常的字符串对象意味着什么?

java - 循环列表以查找特定值

python - 最大、长度、分割 Python

python - 使用 biopython 从外部 pubmed ID 列表中提取多个摘要

python - import skimage 有效,但 skimage.measure 无效