LOL @Alex's regex comment... hopefully there aren't too many haters. With that said however, although they're faster because they're executed in C, regexes aren't my first choice... perhaps i've been biased by the famous jwz quote: '''Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.'''
I will say that solving this homework exercise is tricky because solutions are fraught with errors, as seen in the existing solutions so far. Perhaps this is serendipity because it requires the OP to debug and correct those suggestions instead of just cutting-and-pasting them verbatim into their assignment solution.
As far as the problems go, they include but are not limited to:
- leaving successive spaces
- removing negative signs, and
- merging multiple numbers together
Bottom line... which solutions do I like best? I would start one of the following and debug from there:
For regex, i'll pick:
@Alex's solution or @Matt's if I want just the data instead of the "golden" string
For string processing, I'll modify @Matt's solution to:
keep = set(string.whitespace+string.digits+'+-')
line = ''.join(x for x in line if x in keep)
Finally, @Greg has a good point. Without a clear spec, these are just partial solutions.