Python - Get all substrings of given string
A substring is any contiguous sequence of characters within the string. We'll discuss various methods to extract this substring from a given string by using a simple approach.
Using List Comprehension :
List comprehension offers a concise way to create lists by applying an expression to each element in an iterable. It enables efficient operations like counting characters in a string in a single line of code
s = "abc"
# Generate all substrings using list comprehension
substrings = [s[i:j] for i in range(len(s)) for j in range(i+1, len(s)+1)]
# Print the result
print(substrings)
Output
['a', 'ab', 'abc', 'b', 'bc', 'c']
Explanation:
- Generate substrings using list comprehension: A nested list comprehension is used to create all possible substrings by iterating through all starting (
i) and ending (j) indices in the string. - Print the result: The resulting list
substringscontains all substrings of the strings, and it is printed.
Let's explore various other methods to Get all substrings of a given strings:
Table of Content
Using Nested Loops:
Nested loops in Python allow you to iterate over multiple levels of data, making them useful for tasks like generating substrings. By using a loop inside another loop, you can access each combination of starting and ending indices in a string to extract all substrings.
s = "abc"
# Initialize a list to store substrings
substrings = []
# Use nested loops to generate substrings
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
substrings.append(s[i:j])
print(substrings)
Output
['a', 'ab', 'abc', 'b', 'bc', 'c']
Explanation:
- Generate substrings using nested loops: Two loops are used to iterate through all possible starting (
i) and ending (j) indices of the string, extracting the substrings withtext[i:j]. - Store and print the result: Each generated substring is appended to the
substringslist, and the final list is printed.
Using slice()
slice notation in Python allows you to extract a portion of a string by specifying a start, stop, and optional step. It provides a simple and efficient way to generate substrings by accessing specific ranges of indices directly.
s = "abc"
# Initialize a list to store substrings
substrings = []
# Use slice() to generate all substrings
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
substrings.append(s[slice(i, j)])
print(substrings)
Output
['a', 'ab', 'abc', 'b', 'bc', 'c']
Explanation
- Generate substrings using slice(): Two nested loops iterate through all possible starting (
i) and ending (j) indices, and theslice()function is used to extract substrings from the string using these indices. - Store substrings in a list: Each generated substring is appended to the
substringslist for collection.
Using itertools.combinations():
itertools.combinations() function generates all possible combinations of a given length from an iterable. It is useful for generating substrings of a specific length by specifying the range of indices for each combination.
import itertools
# Define the input string
s = "abc"
# Get all substrings using combinations of indices
substrings = [''.join(s[i:j]) for i, j in itertools.combinations(range(len(s) + 1), 2)]
print(substrings)
Output
['a', 'ab', 'abc', 'b', 'bc', 'c']
Explanation
- Generate combinations of indices: The
itertools.combinations()function generates all pairs of indices (i,j) from the range of indices of the string, which are used to define the start and end points of each substring. - Create substrings: For each pair of indices, the
text[i:j]slices the string, and the substrings are collected in a list using list comprehension.