Python - Get all substrings of given string
Last Updated :
08 Jan, 2025
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
Python
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
substrings
contains all substrings of the string s
, and it is printed.
Let's explore various other methods to Get all substrings of a given strings:
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.
Python
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 with text[i:j]
. - Store and print the result: Each generated substring is appended to the
substrings
list, 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.
Python
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 the slice()
function is used to extract substrings from the string using these indices. - Store substrings in a list: Each generated substring is appended to the
substrings
list for collection.
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.
Python
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.
Similar Reads
Python - All substrings Frequency in String Given a String, extract all unique substrings with their frequency. Input : test_str = "ababa" Output : {'a': 3, 'ab': 2, 'aba': 2, 'abab': 1, 'ababa': 1, 'b': 2, 'ba': 2, 'bab': 1, 'baba': 1} Explanation : All substrings with their frequency extracted. Input : test_str = "GFGF" Output : {'G': 2, 'G
5 min read
Python - All occurrences of substring in string A substring is a contiguous occurrence of characters within a string. Identifying all instances of a substring is important for verifying various tasks. In this article, we will check all occurrences of a substring in String.Using re.finditer()re.finditer() returns an iterator yielding match objects
3 min read
Python | Frequency of substring in given string Finding a substring in a string has been dealt with in many ways. But sometimes, we are just interested to know how many times a particular substring occurs in a string. Let's discuss certain ways in which this task is performed. Method #1: Using count() This is a quite straightforward method in whi
6 min read
Python | Get matching substrings in string The testing of a single substring in a string has been discussed many times. But sometimes, we have a list of potential substrings and check which ones occur in a target string as a substring. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension Using l
6 min read
Python | Get the string after occurrence of given substring The problem involves getting the string that is occurring after the substring has been found. Let's discuss certain ways in which this task can be performed using Python.Using partition()To extract the portion of a string that occurs after a specific substring partition() method is an efficient and
3 min read