Home > Enterprise >  How to get list of substrings within a range of lengths?
How to get list of substrings within a range of lengths?

Time:05-20

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

CodePudding user response:

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)]

CodePudding user response:

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

  • Related