Python Message.content.split()Discord.PY

Python Message.content.split()Discord.PY,python,python-3.x,discord,discord.py,Python,Python 3.x,Discord,Discord.py,我有几个命令可能有多个值,我需要为它们拆分消息。然后问题是我希望能够给用户一个选项,只使用1个值或最多4个值。当我使用message.content.split(“,4)时,我得到一个索引错误,因为它需要4个值。有没有更简单的方法 if message.content.lower().startswith(“!rip”): x=message.content.split(“,4) riptext=x[1] riptext2=x[2] riptext3=x[3] riptext4=x[4] rip

我有几个命令可能有多个值,我需要为它们拆分消息。然后问题是我希望能够给用户一个选项,只使用1个值或最多4个值。当我使用
message.content.split(“,4)
时,我得到一个索引错误,因为它需要4个值。有没有更简单的方法

if message.content.lower().startswith(“!rip”):
x=message.content.split(“,4)
riptext=x[1]
riptext2=x[2]
riptext3=x[3]
riptext4=x[4]
rip=discord.Embed(color=random.randint(0x000000,0xFFFFFF))
rip.set_图像(
url=f“http://www.tombstonebuilder.com/generate.php?top1={quote(riptext)}&top2={quote(riptext2)}&top3={quote(riptext3)}&top4={quote(riptext4)}&sp=“)
等待客户端发送消息(message.channel,embed=rip)

您可以使用以下方法对
split()
输出进行切片以忽略第一项(
“!rip”
):

然后,如果长度小于4,可以用空字符串填充它

请注意,不需要单独的变量
riptext1
riptext2
等。您只需将
riptext
放入一个列表并访问,例如使用
riptext[0]
的第一个元素:

if message.content.lower().startswith('!rip'):
    # store arguments in x, excluding the first element (!rip)
    x = message.content.split(" ",4)[1:]
    # pad x with empty strings in case there are less than 4 arguments, and store the result in riptext
    riptext = x[:4] + ['']*(4 - len(x))
    print(riptext)

    rip = discord.Embed(color=random.randint(0x000000, 0xFFFFFF))
    rip.set_image(
            url=f"http://www.tombstonebuilder.com/generate.php?top1={quote(riptext[0])}&top2={quote(riptext[1])}&top3={quote(riptext[2])}&top4={quote(riptext[3])}&sp=")
    await client.send_message(message.channel, embed=rip)
例如,如果
message.content='!rip 1 2'

  • x
    将是
    ['1','2']
  • riptext
    将是
    ['1'、'2'、''、''、''、'.]

索引从0开始!在修复索引后,您是否仍然存在问题?还有,为什么要使用4个不同的变量?为什么不直接使用x[0],x[1]?@penta我必须保留索引1-4,否则它会使用“!rip”作为第一个值。但是如果我使用的值少于4个,我仍然会得到一个索引器。使用
http://pythontutor.com/visualize.html#mode=display
为了可视化和调试您的代码,我认为您可以使用切片来忽略第一个!这很有道理。我知道我必须在那里的某个地方添加len()来计算项目的数量,但不确定如何处理它。这很有效
if message.content.lower().startswith('!rip'):
    # store arguments in x, excluding the first element (!rip)
    x = message.content.split(" ",4)[1:]
    # pad x with empty strings in case there are less than 4 arguments, and store the result in riptext
    riptext = x[:4] + ['']*(4 - len(x))
    print(riptext)

    rip = discord.Embed(color=random.randint(0x000000, 0xFFFFFF))
    rip.set_image(
            url=f"http://www.tombstonebuilder.com/generate.php?top1={quote(riptext[0])}&top2={quote(riptext[1])}&top3={quote(riptext[2])}&top4={quote(riptext[3])}&sp=")
    await client.send_message(message.channel, embed=rip)