当我尝试拆分单个单词时,我在Python中一直出错。从我读到的,这是因为默认的split()命令查找空格。问题是,我希望第二个分配的变量(在这种情况下为资产)不返回任何值或为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就会输出错误。
如果没有修饰符,我基本上希望能够返回一个语句。但是,没有修饰符会抛出错误。我还能做些什么来解决这个问题吗?有人能指出我在正确的方向吗?
答案 0 :(得分:4)
在Python中,有一种“更好地要求宽恕而非许可”的概念。换句话说,只要尝试你认为可能有效的东西,然后再从中恢复,而不是尝试检查它是否可以起作用。一个例子是尝试访问不存在的列表索引,而不是首先检查列表的长度。关于这种情况有多远可能存在争议,例如here以及其他许多人。
这里最简单的例子是:
command = '!help'
split_string = command.split()
try:
modifiers = split_string[1]
except IndexError: # Well, seems it didn't work
modifiers = None
仅仅except
覆盖所有错误并不是一个好主意。虽然您正在从故障中恢复,但您事先知道可能出现的问题,因此您应该捕获特定的错误。
答案 1 :(得分:3)
解决方法是确保序列中始终至少有两个项目(通过向末尾添加内容)然后切片序列的前两项。
例如:
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
答案 2 :(得分:0)
为什么不首先搜索空格然后再处理分割?
if ' ' in slack_text
:
&LT;你的代码&gt;