Python - Get all possible substrings of a string


Python - Get all possible substrings of a given string

To get all substrings of a given String in Python, iterate over the string across the length of the string for different substring lengths.

Programs

1. Get all possible substrings of given string

In the following program, we take a string in x, and then find all the substrings in it.

We define a function getAllSubStrings() that takes a string and returns all the possible substrings as a list. We use a nested For-loop for this. Inner For-loop to iterate over the length of the string. And, outer For-loop to iterate for different substring lengths.

Python Program

def getAllSubStrings(x):
    #empty string is also a substring
    allSubStrings = [''] 

    #iterate for different substring lengths
    for i in range(0, len(x)):
        #iterate across the length of given string
        for k in range(0, len(x) - i):
            #append substring to resulting list
            allSubStrings.append(x[k:i+k+1])

    return allSubStrings

x = 'apple'
result = getAllSubStrings(x)
print(result)

Output #1

apple
['', 'a', 'p', 'p', 'l', 'e', 'ap', 'pp', 'pl', 'le', 'app', 'ppl', 'ple', 'appl', 'pple', 'apple']

2. Get all possible unique substrings

If we want only unique substrings, then we may use a Set to store the substrings, as shown in the following program.

Python Program

def getAllSubStrings(x):
    #empty string is also a substring
    allSubStrings = {''}

    #iterate for different substring lengths
    for i in range(0, len(x)):
        #iterate across the length of given string
        for k in range(0, len(x) - i):
            #append substring to resulting set
            allSubStrings.add(x[k:i+k+1])

    return allSubStrings

x = input()
result = getAllSubStrings(x)
print(result)

Output #1

aaaaaa
{'', 'aaaaaa', 'a', 'aaaa', 'aaa', 'aa', 'aaaaa'}

References

Summary

In this Python Tutorial, we learned how to find all the possible substrings of a given string.