How to get all possible substrings, then choose K of them in Python

1 Answer

0 votes
def all_substrings(s):
    return [s[i:j] for i in range(len(s)) for j in range(i+1, len(s)+1)]

def get_k_substrings(s, k):
    subs = all_substrings(s)
    return subs[:k]  

result = get_k_substrings("abcdefg", 5)

print(result)


'''
run:

['a', 'ab', 'abc', 'abcd', 'abcde']

'''

 



answered Mar 8 by avibootz

Related questions

...