user4919655
user4919655

Reputation:

How to interpret a list of numbers from a string?

I have number values like:

a="1-5"
b="1,3"
c="1"
d="1,3-5"
e="1-3,5,7-8"
f="0,2-5,7-8,10,14-18"

I want to turn them into full explicit lists of the numbers, like this:

a="1,2,3,4,5"
b="1,3"
c="1"
d="1,3,4,5"
e="1,2,3,5,7,8"
f="0,2,3,4,5,7,8,10,14,15,16,17,18"

Using the re module I can get the numbers:

Like 1 5 in a

But I can't get full range of numbers

ie. 1 2 3 4 5 in a

How can I do this?

Upvotes: 0

Views: 89

Answers (3)

jonrsharpe
jonrsharpe

Reputation: 122061

If you're set on regular expressions, you can pass a custom function as the repl argument to re.sub:

>>> import re
>>> def replacer(match):
    start, stop = map(int, match.groups())
    return ','.join(map(str, range(start, stop+1)))

>>> re.sub('(\d+)-(\d+)', replacer, '1-3,5,7-8')
'1,2,3,5,7,8'

Upvotes: 2

Michael Schmitt
Michael Schmitt

Reputation: 139

You have to treat the range (1 "-" 5) in a special way. Try pythons built in "range" for that.

Best of luck with this exercise.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122352

I see no need to use regular expressions here:

def expand_ranges(string):
    def expand(start, stop):
        return ','.join(map(str, range(int(start), int(stop) + 1)))
    return ','.join([expand(*d.split('-')) if '-' in d else d for d in string.split(',')])

This

  1. splits the input string on commas.
  2. if there is a dash in the string, split on that dash and expand the range to include the intervening numbers
  3. join the results back with commas.

Demo with each of your test cases:

>>> expand_ranges("1-5")
'1,2,3,4,5'
>>> expand_ranges("1,3")
'1,3'
>>> expand_ranges("1")
'1'
>>> expand_ranges("1,3-5")
'1,3,4,5'
>>> expand_ranges("1-3,5,7-8")
'1,2,3,5,7,8'
>>> expand_ranges("0,2-5,7-8,10,14-18")
'0,2,3,4,5,7,8,10,14,15,16,17,18'

Upvotes: 4

Related Questions