简体   繁体   中英

List all substrings of m <= len <= n python

i'm trying to list all substring of len between a and b from a string in input. I implemented this function but specially the output is incorrect (specially in the end). Can anyone help me to fix this or give me a better solution?

def substrings(s, a, b):
    diff = b-a+1
    l = len(s)
    for i in range(l-a):
        print(s[i:i+a])
        for j in range(1, diff):
            sub = s[i:i+a+j]
            print(sub)

substrings('apple', 1, 3) returns

a
ap
app
p
pp
ppl
p
pl
ple
l
le
le

expected:

a
ap
app
p
pp
ppl
p
pl
ple
l
le
e

substrings('apple', 1, 1) returns

a
p
p
l

expected:

a
p
p
l
e

Basically, you have to try every substring but checking its length before (assuming a and b are in the length interval):

def substrings(s,a,b):
    s_len = len(s)
    for i in range(s_len):
        for j in range(i+1,s_len + 1):
            if a <= j-i <= b:
                print(s[i:j])

substrings("apple",1,3)
substrings("apple",1,1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM