I keep getting an error in Python when I try to split a single word. From what I read, this is because the default split() command looks for whitespace. The problem is, I want the second assigned variable (asset in this case) to return nothing or null. This is what I am working with:
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>)"
So with this code, I can type '!help ships' in Slack and cast no error and return the getAllShips() function. But if I type simply '!help', Python casts an error.
I basically want to be able to return a statement if there is no modifier. However, not having a modifier casts an error. Is there something else I can do to approach this problem? Can someone point me in the right direction here?
One solution is to make sure there are always at least two items in the sequence (by adding something to the end) then slice the first two items of the sequence.
For example:
command, asset = (slack_text.split() + [None])[:2]
or:
command, asset, *_ = slack_text.split() + [None]
(here the variable _
ends up with any extra items)
Of course you could also just do it the old-fashioned way:
command = slack_text.split()[:2]
if len(command) > 1:
command, asset = command
else:
command, asset = command[0], None
In Python there is a notion of "better to ask for forgiveness than permission". In other words, just try what you think might work and then recover from it if it doesn't, rather than try check that it might work in the first place. An example would be trying to access a list index that doesn't exist, rather than checking the length of the list first. There are debates about how far this goes e.g. here among many others.
The simplest example here would be:
command = '!help'
split_string = command.split()
try:
modifiers = split_string[1]
except IndexError: # Well, seems it didn't work
modifiers = None
It's not a good idea to just blanket except
all errors. Although you're recovering from a failure, you know beforehand what might go wrong here so you should catch that specific error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With