Skip to content Skip to sidebar Skip to footer

Python 3.6 Split() Not Enough Values To Unpack Workaround?

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

Solution 1:

The 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 = commandelse:
     command, asset = command[0], None

Solution 2:

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.

Solution 3:

Why not search for white space first and then process the split?

if ' ' in slack_text:

< your code >

Post a Comment for "Python 3.6 Split() Not Enough Values To Unpack Workaround?"