Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Frequency of substring in given string
Next article icon

Python – Get all substrings of given string

Last Updated : 08 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Table of Content

  • Using Nested Loops:
  • Using slice()
  • Using itertools.combinations():

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.

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.

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.


Next Article
Python | Frequency of substring in given string
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

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 object
    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
  • Python | Count overlapping substring in a given string
    Given a string and a sub-string, the task is to get the count of overlapping substring from the given string. Note that in Python, the count() function returns the number of substrings in a given string, but it does not give correct results when two occurrences of the substring overlap. Consider thi
    2 min read
  • Get Second Occurrence of Substring in Python String
    We are given a string and a substring, and our task is to find the index of the second occurrence of that substring within the string. This means we need to identify not just if the substring exists, but where it appears for the second time. For example, if we have a string like "hello world, hello
    2 min read
  • Python | Remove the given substring from end of string
    Sometimes we need to manipulate our string to remove extra information from the string for better understanding and faster processing. Given a task in which the substring needs to be removed from the end of the string using Python. Remove the substring from the end of the string using Slicing In thi
    3 min read
  • Python | Get the starting index for all occurrences of given substring
    Given a string and a substring, the task is to find out the starting index for all the occurrences of a given substring in a string. Let's discuss a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # to find all occurrences of substring in #
    3 min read
  • Python - Filter Strings combination of K substrings
    Given a Strings list, extract all the strings that are a combination of K substrings. Input : test_list = ["geeks4u", "allbest", "abcdef"], substr_list = ["s4u", "est", "al", "ge", "ek", "def"], K = 3 Output : ['geeks4u'] Explanation : geeks4u made up of 3 substr - ge, ek and s4u. Input : test_list
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences