[英]Issue with split() using maxsplit
Very basic issue I'm sure, I'm trying to set a !status command to change my bot's status. 我敢肯定,这是一个非常基本的问题,我正在尝试设置!status命令来更改我的机器人的状态。 The following code works:
以下代码有效:
@myBot.event
async def on_message(message):
if message.content.startswith('!status'):
m = message.content.split(' ')
await myBot.change_presence(game=discord.Game(name=m[1]))
So nothing really complicated here, it will set the bot's status to whatever I type after !status
. 因此,这里没有什么真正复杂的设置,它将设置机器人的状态为我在
!status
之后键入的内容。
However, it will stop after the first space, because I take m[1]
without a maxsplit
. 但是,它将在第一个空格之后停止,因为我在没有
maxsplit
情况下使用了m[1]
。 Now, if I add maxsplit=1
to my split()
function, I can get everything after the first space in m[1]
. 现在,如果将
maxsplit=1
添加到我的split()
函数中,则可以获取m[1]
第一个空格之后的所有内容。 This seems perfect, right? 这看起来很完美吧? Let's say I just input the same thing as before, something like
!status test
, surprise, it doesn't work, the status doesn't update even though m[1]
only contains test
. 假设我只是输入了与以前相同的内容,例如
!status test
,令人惊讶,它不起作用,即使m[1]
仅包含test
,状态也不会更新。 Why? 为什么? What does
maxsplit=1
really change that I can't see with a print(m[1])
? 我用
print(m[1])
看不到的maxsplit=1
真正改变了什么?
Without maxplit
you don't have everything after the first whitespace, then m[1]
just contains everything between the first and second whitespace (if present). 如果没有
maxplit
,则第一个空格之后没有所有内容,然后m[1]
仅包含第一个和第二个空格之间的所有内容(如果存在)。
With just one whitespace they are identical: 只有一个空格,它们是相同的:
>>> str1 = '!status test'
>>> str1.split()
['!status', 'test']
>>> str1.split(maxsplit=1)
['!status', 'test']
But with more than one they aren't: 但不止一个,它们不是:
>>> str2 = '!status test debug'
>>> str2.split() # 3 elements
['!status', 'test', 'debug']
>>> str2.split(maxsplit=1) # 2 elements
['!status', 'test debug']
I think what you really want is to strip away the !status
: 我认为您真正想要的是删除
!status
:
>>> str1[len('!status '):] # or hardcode the length: `[8:]`
'test'
>>> str2[len('!status '):]
'test debug'
Or even easier str.partition
: 甚至更简单的
str.partition
:
>>> str1 = '!status test'
>>> str2 = '!status test debug'
>>> str1.partition(' ')
('!status', ' ', 'test')
>>> str2.partition(' ')
('!status', ' ', 'test debug')
There the third element always contains everything after the first whitespace. 在那里,第三个元素始终包含第一个空格之后的所有内容。 You could even check if the first element
== '!status'
您甚至可以检查第一个元素是否
== '!status'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.