Python 3.6 Split() 没有足够的值来解压解决方法?

sln*_*d54 1 python python-3.x

当我尝试拆分单个单词时,我一直在 Python 中遇到错误。从我读到的,这是因为默认的 split() 命令查找空格。问题是,我希望第二个分配的变量(在这种情况下为资产)不返回任何内容或返回空值。这就是我正在使用的:

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>)"
Run Code Online (Sandbox Code Playgroud)

因此,使用此代码,我可以在 Slack 中键入 '!help ship' 并且没有错误并返回 getAllShips() 函数。但是如果我简单地输入 '!help',Python 就会抛出一个错误。

如果没有修饰符,我基本上希望能够返回一个语句。但是,没有修饰符会引发错误。我还能做些什么来解决这个问题?有人可以在这里指出我正确的方向吗?

kin*_*all 5

解决方案是确保序列中始终至少有两个项目(通过在末尾添加一些内容),然后对序列的前两个项目进行切片。

例如:

command, asset = (slack_text.split() + [None])[:2]
Run Code Online (Sandbox Code Playgroud)

或者:

command, asset, *_ = slack_text.split() + [None]
Run Code Online (Sandbox Code Playgroud)

(这里变量_以任何额外的项目结束)

当然,你也可以用老式的方式来做:

 command = slack_text.split()[:2]
 if len(command) > 1:
     command, asset = command
 else:
     command, asset = command[0], None
Run Code Online (Sandbox Code Playgroud)


rog*_*osh 5

在 Python 中有一个概念“请求宽恕比许可更好”。换句话说,只需尝试您认为可能有效的方法,然后在无效时从中恢复,而不是首先尝试检查它是否有效。一个例子是尝试访问一个不存在的列表索引,而不是首先检查列表的长度。有关于这会走多远的争论,例如这里等等。

这里最简单的例子是:

command = '!help'
split_string = command.split()
try:
    modifiers = split_string[1]
except IndexError: # Well, seems it didn't work
    modifiers = None
Run Code Online (Sandbox Code Playgroud)

仅仅覆盖except所有错误并不是一个好主意。尽管您正在从失败中恢复,但您事先知道这里可能会出现什么问题,因此您应该捕获该特定错误。