Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

All possible substring in python

I wanna print all possible substring from a given a string in python. But I'm stuck, I cant figure out the logic on how to get all possible substring. Please explain to me with python code.Thank you.

2 Answers

Steven Parker
Steven Parker
229,607 Points

Is this a project in one of the courses? If so, you could give a link to the course page.

One possible method would be two use two loops. The first loop would go through all the letters of the string, making it be the start of the substring. Then the 2nd loop would go through all possible lengths of the substring (from that letter to the end, or less). But be aware that "all possible substrings" could be very many unless the string is very short!

Try coding it with that concept in mind, and if you have trouble post the code you have at that point.


UPDATE: You're close, but you need the starting index (number). And the ending range needs to be based on the start. Finally, use a slice to get the substring:

for i in range(len(s)):       # pick the first letter
  for m in range(i, len(s)):  # pick the last letter
    print(s[i:m+1])           # print the substring (slice)

I'm stuck here. can you please help me with the code? s = 'abc' for i in s: for m in range(len(s)-1):