Examples
- Palindrome Program in Python (Check String is Palindrome or Not)
- Program to Remove Punctuations From String in Python
- Remove a Character from String in Python (Program With Examples)
- Remove Stop Words from String in Python Using NLTK and spaCy
- Program to Sort Words in Alphabetical Order in Python (Arrange in Alphabetic Order)
- How to Sort Strings in Python? (Program With Examples)
- How to Count Vowels in Python String? Vowels Program in Python
- How to Remove Vowels from String in Python? Program With Examples
- How to Convert String to Int or Float in Python? String Parse Program
- How to Convert Float to Int in Python? Program With Examples
- How to Convert Int to String in Python? Program with Examples
- Remove Spaces from String in Python (Trim Whitespace)
- Python Program to Check If Two Strings are Anagram
- How to Capitalize First Letter in Python? String Capitalization Program
- Find All Permutations of String in Python (Programs and Examples)
- Find All Substrings of a String in Python (Programs with Examples)
- Create Multiline String in Python (With & Without New Line)
Find All Substrings of a String in Python (Programs with Examples)
Substrings in Python are smaller fragments of a larger string that can be extracted based on specific positions or patterns. It is a fundamental operation in Python to get substrings of a string, enabling you to isolate and extract relevant information from textual data.
In this tutorial, we will learn how to print all substrings from a string. Whether you're a beginner seeking to enhance your Python skills or an experienced developer looking to master the art of text manipulation, this tutorial is for you.
Use Cases of Python Program to Get Substrings of String:
-
Data Extraction and Parsing: Extracting substrings is vital in data extraction tasks, where you need to retrieve specific information from larger text bodies. By obtaining substrings based on defined patterns or delimiters, you can parse structured data, extract relevant fields, or isolate valuable information for further processing.
-
Text Manipulation and Formatting: Substrings allow you to manipulate and format text efficiently. By extracting smaller fragments from a larger string, you can perform various operations such as concatenation, replacement, or formatting, enabling you to generate customized outputs or transform textual data as needed.
-
Text Search and Analysis: Substrings play a significant role in text search and analysis tasks. Whether you're searching for specific keywords or analyzing linguistic patterns, extracting substrings based on matching criteria empowers you to uncover valuable insights, detect patterns, or perform advanced text analysis.
To practice and reinforce the concepts covered below, we recommend using the online Python compiler by Tutorials Freak. It offers a user-friendly interface, allowing you to write, run, and experiment with Python Programs directly in your web browser.
Find All Substrings of a String in Python
To find all substrings of a string in Python, you can use nested loops to iterate over all possible starting and ending indices.
Code
def find_substrings(string):
substrings = []
for i in range(len(string)):
for j in range(i + 1, len(string) + 1):
substrings.append(string[i:j])
return substrings
# Example usage
input_string = "abc"
substrings_list = find_substrings(input_string)
print(substrings_list)
Output
['a', 'ab', 'abc', 'b', 'bc', 'c']
Explanation
In this program, the find_substrings function takes a string as input. It initializes an empty list substrings to store the substrings.
The outer loop iterates over the starting index i from 0 to the length of the string. The inner loop iterates over the ending index j from i+1 to len(string) + 1. This ensures that all possible substrings starting from index i are considered.
For each pair of indices i and j, the substring from index i to index j-1 is obtained using string slicing (string[i:j]). The substring is then appended to the substrings list.
Finally, the function returns the substrings list containing all the substrings of the input string.
Print All Substrings of a String Using Recursion
To print all substrings of a string in Python using recursion, you can define a recursive function that gradually generates and prints substrings.
Code
def print_substrings(string):
if len(string) == 0:
return
for i in range(len(string)):
for j in range(i + 1, len(string) + 1):
print(string[i:j])
print_substrings(string[1:])
# Example usage
input_string = "abc"
print_substrings(input_string)
Output
a
ab
abc
b
bc
c
Explanation
In this program, the print_substrings function takes a string as input. It uses a recursive approach to generate and print substrings.
The base case of the recursion is when the string is empty, in which case the function simply returns.
For each recursive call, the function uses two nested loops to iterate over the starting and ending indices of substrings. The outer loop determines the starting index i from 0 to the length of the string.
The inner loop determines the ending index j from i+1 to len(string) + 1. This ensures that all possible substrings starting from index i are considered.
For each pair of indices i and j, the function prints the substring from index i to index j-1 using string slicing (string[i:j]).
After printing all the substrings for the current call, the function makes a recursive call to print_substrings with the updated string obtained by excluding the first character (string[1:]). This recursive call continues the process of generating and printing substrings for the remaining portion of the string.
Find Number of Substrings in a String in Python
To find the number of substrings in a string, you can use a formula based on the length of the string. The formula to calculate the number of substrings in a string of length n is n * (n + 1) / 2.
Code
def count_substrings(string):
n = len(string)
count = n * (n + 1) // 2
return count
# Example usage
input_string = "tutorialsfreak"
substrings_count = count_substrings(input_string)
print(substrings_count)
Output
105
Explanation
In this program, the count_substrings function takes a string as input. It calculates the length of the string n using the len() function.
The number of substrings can be calculated using the formula n * (n + 1) / 2. However, in Python, the division operator / returns a floating-point result. Since the number of substrings should be an integer, the // operator is used for integer division to get the count as an integer.
The function returns the calculated count of substrings.