All possible substrings of a string in Python 2

 

st="abcde"
li=list()
for i in range(0,len(st)):
    for j in range(i,len(st)):
        substring = ""
        for k in range(i,j+1):
           substring+=st[k]
        li.append(substring)
print li

output: ['a', 'ab', 'abc', 'abcd', 'abcde', 'b', 'bc', 'bcd', 'bcde', 'c', 'cd', 'cde', 'd', 'de', 'e']

 

Leave a comment