I had the same issue and there is a perfect solution to it -zfill method

An example of usage:

>>> str('1').zfill(7)
'0000001'

What you need to do is to create a generator for N numbers and fill its string representation with zeros.

>>> for i in range(1, 18):
...     str(i).zfill(2)
...
'01'
'02'
'03'
...
'16'
'17'
Answer from taras on Stack Overflow
๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-range.html
Python range() Function
The most common form is range(n), given integer n returns a numeric series starting with 0 and extending up to but not including n, e.g. range(6) returns 0, 1, 2, 3, 4, 5. With Python's zero-based indexing, the contents of a string length 6, are at index numbers 0..5, so range(6) will produce ...
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ python range to the list of strings | example code
Python range to the list of strings | Example code - EyeHunts
August 27, 2021 - Python simple example code. There is a perfect solution to it -zfill method. Generator for N numbers and fill its string representation with zeros. list1 = [] for i in range(1, 7): list1.append(str(i).zfill(2)) print(list1) Output: lst = range(11) ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_func_range.asp
Python range() Function
Remove List Duplicates Reverse a String Add Two Numbers ยท Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-convert-string-ranges-to-list
Python | Convert String ranges to list | GeeksforGeeks
May 16, 2023 - In this, the split is performed on hyphens and comma and accordingly range, numbers are extracted and compiled into a list. ... # Python3 code to demonstrate working of # Convert String ranges to list # Using sum() + list comprehension + enumerate() + split() # initializing string test_str = "1, 4-6, 8-10, 11" # printing original string print("The original string is : " + test_str) # Convert String ranges to list # Using sum() + list comprehension + enumerate() + split() res = sum(((list(range(*[int(b) + c for c, b in enumerate(a.split('-'))])) if '-' in a else [int(a)]) for a in test_str.split(', ')), []) # printing result print("List after conversion from string : " + str(res))
๐ŸŒ
YouTube
youtube.com โ€บ watch
python range to string list - YouTube
Download this code from https://codegive.com In Python, the range function is commonly used to generate a sequence of numbers. While range itself returns a r...
Published ย  February 2, 2024
Find elsewhere
Top answer
1 of 5
6

One approach could be "eating" piece by piece the input sequence and store the partial range results untill you've got them all:

def formatter(start, end, step):
    return '{}-{}:{}'.format(start, end, step)
    # return '{}-{}:{}'.format(start, end + step, step)

def helper(lst):
    if len(lst) == 1:
        return str(lst[0]), []
    if len(lst) == 2:
        return ','.join(map(str,lst)), []

    step = lst[1] - lst[0]
    for i,x,y in zip(itertools.count(1), lst[1:], lst[2:]):
        if y-x != step:
            if i > 1:
                return formatter(lst[0], lst[i], step), lst[i+1:]
            else:
                return str(lst[0]), lst[1:]
    return formatter(lst[0], lst[-1], step), []

def re_range(lst):
    result = []
    while lst:
        partial,lst = helper(lst)
        result.append(partial)
    return ','.join(result)

I test it with a bunch of unit tests and it passed them all, it can handle negative numbers too, but they'll look kind of ugly (it's really anybody's fault).

Example:

>>> re_range([1,  4,5,6, 10, 15,16,17,18, 22, 25,26,27,28])
'1,4-6:1,10,15-18:1,22,25-28:1'
>>> re_range([1, 3, 5, 7, 8, 9, 10, 11, 13, 15, 17])
'1-7:2,8-11:1,13-17:2'

Note: I wrote the code for Python 3.


Performance

I didn't put any performance effort in the solution above. In particular, every time a list get re-builded with slicing, it might take some time if the input list has a particular shape. So, the first simple improvement would be using itertools.islice() where possible.

Anyway here's another implementation of the same algorithm, that scan through the input list with a scan index instead of slicing:

def re_range(lst):
    n = len(lst)
    result = []
    scan = 0
    while n - scan > 2:
        step = lst[scan + 1] - lst[scan]
        if lst[scan + 2] - lst[scan + 1] != step:
            result.append(str(lst[scan]))
            scan += 1
            continue

        for j in range(scan+2, n-1):
            if lst[j+1] - lst[j] != step:
                result.append(formatter(lst[scan], lst[j], step))
                scan = j+1
                break
        else:
            result.append(formatter(lst[scan], lst[-1], step))
            return ','.join(result)

    if n - scan == 1:
        result.append(str(lst[scan]))
    elif n - scan == 2:
        result.append(','.join(map(str, lst[scan:])))

    return ','.join(result)

I stopped working on it once it got ~65% faster than the previous top solution, it seemed enough :)

Anyway I'd say that there might still be room for improvement (expecially in the middle for-loop).

2 of 5
2

This is a comparison of the 3 methods. Change the amount of data and the density via the values below...no matter what values I use, the first solution seems to be the quickest for me. For very large sets of data, the third solution becomes very slow.

EDITED

Edited to include comments below and add in a new solution. The last solution seems to be the quickest now.

import numpy as np
import itertools
import random
import timeit

# --- My Solution --------------------------------------------------------------
def list_to_ranges1(data):
   data = sorted(data)
   diff_data = np.diff(data)
   ranges = []
   i = 0
   skip_next = False
   for k, iterable in itertools.groupby(diff_data, None):
      rng = list(iterable)
      step = rng[0]
      if skip_next:
         skip_next = False
         rng.pop()

      if len(rng) == 0:
         continue
      elif len(rng) == 1:
         ranges.append('%d' % data[i])
      elif step == 1:
         ranges.append('%d-%d' % (data[i], data[i+len(rng)]+step))
         i += 1
         skip_next = True
      else:
         ranges.append('%d-%d:%d' % (data[i], data[i+len(rng)]+step, step))
         i += 1
         skip_next = True
      i += len(rng)

   if len(rng) == 0 or len(rng) == 1:
      ranges.append('%d' % data[i])
   return ','.join(ranges)

# --- Kaidence Solution --------------------------------------------------------
# With a minor edit for use in range function
def list_to_ranges2(data):
   onediff = np.diff(data)
   twodiff = np.diff(onediff)
   increments, breakingindices = [], []
   for i in range(len(twodiff)):
       if twodiff[i] != 0:
           breakingindices.append(i+2)  # Correct index because of the two diffs
           increments.append(onediff[i]) # Record the increment for this section

  # Increments and breakingindices should be the same size
   str_list = []
   start = data[0]
   for i in range(len(breakingindices)):
       str_list.append("%d-%d:%d" % (start,
                                     data[breakingindices[i]-1] + increments[i],
                                     increments[i]))
       start = data[breakingindices[i]]
   str_list.append("%d-%d:%d" % (start,
                                 data[len(data)-1] + onediff[len(onediff)-1],
                                 onediff[len(onediff)-1]))
   return ','.join(str_list)

# --- Rik Poggi Solution -------------------------------------------------------
# With a minor edit for use in range function
def helper(lst):
    if len(lst) == 1:
        return str(lst[0]), []
    if len(lst) == 2:
        return ','.join(map(str,lst)), []

    step = lst[1] - lst[0]
    #for i,x,y in itertools.izip(itertools.count(1), lst[1:], lst[2:]):
    for i,x,y in itertools.izip(itertools.count(1),
                                itertools.islice(lst, 1, None, 1),
                                itertools.islice(lst, 2, None, 1)):
        if y-x != step:
            if i > 1:
                return '{}-{}:{}'.format(lst[0], lst[i]+step, step), lst[i+1:]
            else:
                return str(lst[0]), lst[1:]
    return '{}-{}:{}'.format(lst[0], lst[-1]+step, step), []

def list_to_ranges3(lst):
    result = []
    while lst:
        partial,lst = helper(lst)
        result.append(partial)
    return ','.join(result)

# --- Rik Poggi Solution 2 -----------------------------------------------------
def formatter(start, end, step):
    #return '{}-{}:{}'.format(start, end, step)
    return '{}-{}:{}'.format(start, end + step, step)

def list_to_ranges4(lst):
    n = len(lst)
    result = []
    scan = 0
    while n - scan > 2:
        step = lst[scan + 1] - lst[scan]
        if lst[scan + 2] - lst[scan + 1] != step:
            result.append(str(lst[scan]))
            scan += 1
            continue

        for j in xrange(scan+2, n-1):
            if lst[j+1] - lst[j] != step:
                result.append(formatter(lst[scan], lst[j], step))
                scan = j+1
                break
        else:
            result.append(formatter(lst[scan], lst[-1], step))
            return ','.join(result)

    if n - scan == 1:
        result.append(str(lst[scan]))
    elif n - scan == 2:
        result.append(','.join(itertools.imap(str, lst[scan:])))

    return ','.join(result)

# --- Test Function ------------------------------------------------------------
def test_data(data, f_to_test):
   data_str = f_to_test(data)
   _list = []
   for r in data_str.replace('-',':').split(','):
      r = [int(a) for a in r.split(':')]
      if len(r) == 1:
         _list.extend(r)
      elif len(r) == 2:
         _list.extend(range(r[0], r[1]))
      else:
         _list.extend(range(r[0], r[1], r[2]))
   return _list

# --- Timing Tests -------------------------------------------------------------
# Generate some sample data...
data_list = []
for i in range(5):
   # Note: using the "4000" and "5000" values below, the relative density of
   # the data can be changed.  This has a huge effect on the results
   # (particularly on the results for list_to_ranges3 which uses recursion).
   data_list.append(sorted(list(set([random.randint(1,4000) for a in \
                                      range(random.randint(5,5000))]))))

testfuncs = list_to_ranges1, list_to_ranges2, list_to_ranges3, list_to_ranges4
for f in testfuncs:
   print '\n', f.__name__
   for i, data in enumerate(data_list):
      t = timeit.Timer('f(data)', 'from __main__ import data, f')
      #print f(data)
      print i, data==test_data(data, f), round(t.timeit(200), 3)
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 68491454 โ€บ using-range-function-in-python
loops - Using range function in Python - Stack Overflow
You need to concatenate i.upper() to a new string. ... Every string in Python ist iterable, so don't use another generator like range. But if your string is "a b c d e f g", every second element is a space " ". Here you'd use for i in "a b c d e f g".split(" ") ;) (and concatenate in a new variable as Barmar said) ... Your example doesn't work, because i = i.upper() does not reassign the uppercase letter back to the original string.
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ python range() explained with examples
Python range() Function Explained with Examples
March 17, 2022 - So it means range() produces numbers one by one as the loop moves to the next iteration. It saves lots of memory, which makes range() faster and more efficient. ... You can iterate Python sequence types such as list and string using a range() and for loop.
๐ŸŒ
Real Python
realpython.com โ€บ python-range
Python range(): Represent Numerical Ranges โ€“ Real Python
November 24, 2024 - In this range, you use the arguments to calculate number times each integer from one to ten. In particular, the last step argument makes sure that numbers in each row are correctly spaced out. To format the table, you use an f-string and the end parameter of print(), which keeps each number on the same line. In this example...
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-convert-numeric-string-range-to-a-list
How to Convert Numeric String Range to a List in Python?
To convert numeric string range like '4-9' to a list like [4, 5, 6, 7, 8, 9] in Python: split the string using hyphen as delimiter, convert the splits to integers, create a range using these integers, and then convert the range to a list.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ stdtypes.html
Built-in Types โ€” Python 3.14.6 documentation
The linspace recipe shows how to implement a lazy version of range suitable for floating-point applications. The following table summarizes the text and binary sequence types methods by category. Textual data in Python is handled with str objects, or strings.
๐ŸŒ
Python
docs.python.org โ€บ 3.3 โ€บ library โ€บ stdtypes.html
https://docs.python.org/3.3/library/stdtypes.html?...
January 23, 2022 - Changed in version 3.3: Define โ€˜==โ€™ and โ€˜!=โ€™ to compare range objects based on the sequence of values they define (instead of comparing based on object identity). New in version 3.3: The start, stop and step attributes. Textual data in Python is handled with str objects, or strings.
๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ string โ€บ string-alphabet-range-python
String - Alphabet Range in Python - AskPython
May 30, 2023 - In this article, weโ€™re going to explore strings in Python and, more specifically, the string module of Python and learn to get a range of alphabets as a string and manipulate strings using different functionalities available in Python.
๐ŸŒ
Stanford
web.stanford.edu โ€บ class โ€บ archive โ€บ cs โ€บ cs106a โ€บ cs106a.1204 โ€บ handouts โ€บ py-range.html
Python range() Function
The most common form is range(n), for integer n, which returns a numeric series starting with 0 and extending up to but not including n, e.g. range(5) returns 0, 1, 2, 3, 4. This is perfect for generating the index numbers into, for example, a string.. >>> s = 'Python' >>> len(s) 6 >>> for ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_range.asp
Python range
Remove List Duplicates Reverse a String Add Two Numbers ยท Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... The built-in range() function returns an immutable sequence of numbers, commonly used for looping a specific number of times.