当我尝试拆分单个单词时,我在 Python 中不断遇到错误。据我所知,这是因为默认的 split() 命令会查找空格。问题是,我希望第二个分配的变量(在本例中为 Assets )不返回任何内容或返回 null。这就是我正在使用的:
slack_text.startswith("!help"):
command, asset = slack_text.split()
if asset != "":
if asset == "commandlist":
slack_reply = "Available Commands: !addme, !getBalance, !buy <asset> <quantity>"
elif asset == "ships":
slack_reply = getAllShips()
elif asset == "buildings":
slack_reply = getAllBuildings()
elif shipExists(asset):
slack_reply = getShip(asset)
elif buildingExists(asset):
slack_reply = getBuilding(asset)
else:
slack_reply = "Not a valid asset."
else:
slack_reply = "Available help modifiers are: commandlist, <ship_name>, <building_name>. (!help <modifier>)"
因此,使用这段代码,我可以在 Slack 中键入“!help ships”,并且不会出现错误并返回 getAllShips() 函数。但是,如果我简单地键入“!help”,Python 就会抛出一个错误。
我基本上希望能够在没有修饰符的情况下返回一个语句。但是,没有修饰符会引发错误。我还能做些什么来解决这个问题吗?有人可以在这里为我指明正确的方向吗?
请您参考如下方法:
一个解决方案是确保序列中始终至少有两项(通过在末尾添加一些内容),然后将序列的前两项切片。
例如:
command, asset = (slack_text.split() + [None])[:2]
或:
command, asset, *_ = slack_text.split() + [None]
(这里的变量 _ 以任何额外的项目结束)
当然你也可以用老式的方式来做:
command = slack_text.split()[:2]
if len(command) > 1:
command, asset = command
else:
command, asset = command[0], None
