dan
dan

Reputation: 3519

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. 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.

However, it will stop after the first space, because I take m[1] without a maxsplit. Now, if I add maxsplit=1 to my split() function, I can get everything after the first space in 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. Why? What does maxsplit=1 really change that I can't see with a print(m[1])?

Upvotes: 0

Views: 3611

Answers (1)

MSeifert
MSeifert

Reputation: 152765

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).

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:

>>> str1[len('!status '):]  # or hardcode the length: `[8:]`
'test'

>>> str2[len('!status '):]
'test debug'

Or even easier 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'

Upvotes: 1

Related Questions