'How to get list of substrings within a range of lengths?

I’m trying to figure out how to get a list of all substrings within a given range of lengths. For example, I have a string of n= 123456789 and I need to get all substrings between mmin and mmax. Let’s define mmin=7 and mmax=9. How would you loop over the range of 7 to 9 to produce a list of substrings from n with a length that is within the range? The function should be dynamic to handle any range as long as it doesn’t exceed the length of the initial string. I’m expecting substrings with a length of 7,8,9



Solution 1:[1]

You can use list comps

#if you want empty substrings
def find_substrings(n,mmin,mmax):
  return[n[i:i+j] for j in range(mmax-mmin) for i in range(mmin,mmax)]
#if you don't want empty substrings
def find_substrings(n,mmin,mmax):
  return[n[i:i+j] for j in range(1,mmax-mmin) for i in range(mmin,mmax)]

Solution 2:[2]

if mmax < len(n): sub_string = [] for i in range(mmin, mmax): sub_string.append(n[i])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mous
Solution 2 aalexmann