Change language

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

Python | Get all substrings of a given string Python functions: Questions

Python | Get all substrings of a given string String Variables: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method

# 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) )