Python | Get all substrings of a given string



Method # 1: Using a list of lists + slicing strings
A combination of list comprehension and slicing strings can be used to accomplish this particular task. It`s just a brute force method to accomplish this task.

# Python3 code to demonstrate how it works
# Get all substrings of a string
# Using comprehension list + line slice

 
# initialization string

test_str = "Geeks"

 
# print original string

print ( "The original string is:" + str (test_str))

 
< code class = "comments"> # Get all substrings of a string
# Using comprehension list + line slice

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

  for j in range (i + 1 , len (test_str) + 1 )]

 
# print 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 done using the built-in combination function, which helps to get all possible combinations, i.e. substrings from a string.

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`]


# Python3 code to demonstrate how it works
# Get all substrings of a string
# Using itertools.combination ()

from itertools import combinations

 
# initialization string

test_str = "Geeks"

  
# print the original line

print ( "The original string is:" + str (test_str))

 
# Get everything substrings of a string
# Using ite rtools.combination ()

res = [test_str [x: y] for x, y in combinations (

range ( len (test_str) + 1 ), r = 2 )]

  
# print result

print ( "All substrings of string are:" + str (res) )