使用maxsplit的split()问题

时间:2017-05-20 14:18:08

标签: python string python-3.x discord discord.py

非常基本的问题我确定,我尝试设置!状态命令来更改机器人的状态。以下代码有效:

@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]))

所以这里没有什么真正复杂的,它会将机器人的状态设置为我在!status后输入的内容。

但是,它会在第一个空格后停止,因为我在没有m[1]的情况下使用maxsplit。现在,如果我将maxsplit=1添加到split()函数,我可以在m[1]中的第一个空格之后获取所有内容。这看起来很完美,对吗?让我们说我只是输入与之前相同的东西,例如!status test,惊讶,它不起作用,即使m[1]仅包含状态,状态也不会更新test。为什么? maxsplit=1真正改变了什么,我无法用print(m[1])看到什么?

1 个答案:

答案 0 :(得分:1)

如果没有maxplit,您就不会在第一个空格之后拥有所有内容,那么m[1] 只是包含第一个和第二个空格(如果存在)之间的所有内容。< / p>

只有一个空格,它们是相同的:

>>> str1 = '!status test'
>>> str1.split()
['!status', 'test']

>>> str1.split(maxsplit=1)
['!status', 'test']

但不止一个人他们不是:

>>> str2 = '!status test debug'
>>> str2.split()            # 3 elements
['!status', 'test', 'debug']

>>> str2.split(maxsplit=1)  # 2 elements
['!status', 'test debug']

我认为你真正想要的是剥离!status

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

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

甚至更轻松str.partition

>>> str1 = '!status test'
>>> str2 = '!status test debug'
>>> str1.partition(' ')
('!status', ' ', 'test')
>>> str2.partition(' ')
('!status', ' ', 'test debug')

第三个元素总是包含第一个空格之后的所有内容。你甚至可以检查第一个元素== '!status'