Python – Get all substrings of given string



Python | Get all substrings of given string

There are many problems in which we require to get all substrings of a string. This particular utility is very popular in competitive programming and having shorthands to solve this problem can always be handy. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using list comprehension + string slicing
The combination of list comprehension and string slicing can be used to perform this particular task. This is just brute force method to perform this task.

 

# Python3 code to demonstrate working of
# Get all substrings of string
# Using list comprehension + string slicing
 
# initializing string 
test_str = "Geeks"
 
# printing original string 
print("The original string is : " + str(test_str))
 
# Get all substrings of string
# Using list comprehension + string slicing
res = [test_str[i: j] for i in range(len(test_str))
          for j in range(i + 1, len(test_str) + 1)]
 
# printing result 
print("All substrings of string are : " + str(res))

Output :

The original string is : Geeks
All substrings of string are : [‘G’, ‘Ge’, ‘Gee’, ‘Geek’, ‘Geeks’, ‘e’, ‘ee’, ‘eek’, ‘eeks’, ‘e’, ‘ek’, ‘eks’, ‘k’, ‘ks’, ‘s’]

 

Method #2 : Using itertools.combinations()
This particular task can also be performed using the inbuilt function of combinations, which helps to get all the possible combinations i.e the substrings from a string.

# Python3 code to demonstrate working of
# Get all substrings of string
# Using itertools.combinations()
from itertools import combinations
 
# initializing string 
test_str = "Geeks"
 
# printing original string 
print("The original string is : " + str(test_str))
 
# Get all substrings of string
# Using itertools.combinations()
res = [test_str[x:y] for x, y in combinations(
            range(len(test_str) + 1), r = 2)]
 
# printing result 
print("All substrings of string are : " + str(res))

Output :

The original string is : Geeks
All substrings of string are : [‘G’, ‘Ge’, ‘Gee’, ‘Geek’, ‘Geeks’, ‘e’, ‘ee’, ‘eek’, ‘eeks’, ‘e’, ‘ek’, ‘eks’, ‘k’, ‘ks’, ‘s’]

Last Updated on November 13, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs