Find all substrings of a string Python | Example code

The substrings of a string are the character or the group of characters that are present inside the given string. To Find all substrings of a string you can use list comprehension + string slicing or itertools.combinations() in Python

Example Get all substrings from a string in python

Simple python examples code:

Using list comprehension + string slicing

It’s a brute force method to get all substrings.

test_str = "Python"

res = [test_str[i: j] for i in range(len(test_str))
       for j in range(i + 1, len(test_str) + 1)]

print(res)

Output:

Find all substrings of a string Python

Using itertools.combinations()

This method has combinations of functions to get all the possible combinations i.e the substrings from a string.

You have to import combinations.

from itertools import combinations

test_str = "Python"

res = [test_str[x:y] for x, y in combinations(
    range(len(test_str) + 1), r=2)]

print(res)

Output: it will same because the given string is the same in the example.

Is there a way to print all substrings of a string in O(n) time?

Answer: Do it without a nested loop with a random library, but the execution time is similar to your code.

from random import randint

list1 = []
str1 = 'abc'
while len(list1) != int(((len(str1) + 1) * len(str1)) // 2):
    i = randint(0, len(str1))
    j = randint(0, len(str1))
    i, j = max(i, j), min(i, j)
    if i != j:
        a = str1[j:i]
        if a not in list1:
            list1.append(a)
            print(a)

Output:

b
abc
ab
bc
c
a

Source: stackoverflow.com

Do comment if you have any doubts and suggestions on this Python string topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.