Login

Pattern to integer list function

Author:
marinho
Posted:
December 1, 2007
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

This function can be util for transform pattern strings like these to list:

>>> pattern_to_list('42-45')
[42, 43, 44, 45]

>>> pattern_to_list('15,49-52')
[15, 49, 50, 51, 52]

>>> pattern_to_list('0-13')
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

You can use also the list to pattern function at http://www.djangosnippets.org/snippets/496/

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def pattern_to_list(self, pattern):
    ret = []

    for e1 in pattern.split(','):
        if e1.strip().isdigit():
            ret.append(int(e1.strip()))
        elif e1.strip().find('-') >= 0:
            s, e = e1.strip().split('-')
            ret += range(int(s.strip()), int(e.strip())+1)

    return ret

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.