Python Message.content.split()Discord.PY
我有几个命令可能有多个值,我需要为它们拆分消息。然后问题是我希望能够给用户一个选项,只使用1个值或最多4个值。当我使用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
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'、''、''、''、'.]
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)