Let's say I want to parse audio track information into two variables like this:
'2/15'
->track = 2, num_tracks = 15
'7'
->track = 7, num_tracks = None
What's an elegant way to do this in Python? For example:
track, num_tracks = track_info.split('/')
This works for the first format, but not for the second, raising ValueError: need more than 1 value to unpack. So I came up with this:
try:
track, num_tracks = track_info.split('/', 1)
except:
track, num_tracks = track_info, None
How can this be more elegant or better?
except
though; catch specific exceptions only. You'd be amazed how many bugs could be masked by blanketexcept
statements. \$\endgroup\$