For this task, I definitely use a regex:
import re there = re.compile(r'\s*(\d+)\s*(\S+)') thematch = there.match(s) if thematch: number, unit = thematch.groups() else: raise ValueError('String %r not in the expected format' % s)
In the RE pattern, \s means spaces, \d means number, \s means non-spaces; * means "0 or more of the preceding", + means "1 or more of the preceding", and parentheses enclose "capture groups", which are then returned by calling groups() on the match object. thematch - None if the given string does not match the pattern: optional spaces, then one or more numbers, then optional spaces, then one or more non-white characters).
source share