1

Can anyone help me with finding all the possible substring in a string using python?

E.g:

string = 'abc'

output

a, b, c, ab, bc, abc

P.s : I am a beginner and would appreciate if the solution is simple to understand.

Sahil
  • 1,387
  • 14
  • 41
VipuL ShiNde
  • 59
  • 1
  • 6
  • 1
    What have you tried so far? Please share your code. – Brenden Price May 24 '20 at 22:52
  • 2
    So there cannot be `ac`? Thats kinda important – John May 24 '20 at 22:53
  • as of now i am able to find the substrings if its given by the user eg if i need to find cdc in ABCDCDC. for i in range(len(s1)): print(s1[i:i+3]) – VipuL ShiNde May 24 '20 at 22:54
  • 2
    Check out [print substrings given string](https://www.geeksforgeeks.org/program-print-substrings-given-string/) – DarrylG May 24 '20 at 22:54
  • Same question, but Python 2 so I wouldn't call it a duplicate: [How To Get All The Contiguous Substrings Of A String In Python?](https://stackoverflow.com/q/22469997/4518341) – wjandrea May 24 '20 at 22:58

4 Answers4

4

You could do something like:

for length in range(len(string)):
    for index in range(len(string) - length):
        print(string[index:index+length+1])

Output:

a
b
c
ab
bc
abc
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Math chiller
  • 4,123
  • 6
  • 28
  • 44
2

else one way is using the combinations

from itertools import combinations
s = 'abc'
[
    ''.join(x)
    for size in range(1, len(s) + 1)
    for x in  (combinations(s, size))
]

Out

['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
0

Every substring contains a unique start index and a unique end index (which is greater than the start index). You can use two for loops to get all unique combinations of indices.

def all_substrings(s):
    all_subs = []
    for end in range(1, len(s) + 1):
        for start in range(end):
            all_subs.append(s[start:end])
    return all_subs
s = 'abc'
print(all_substrings(s)) # prints ['a', 'ab', 'b', 'abc', 'bc', 'c']
Varun Nayak
  • 290
  • 1
  • 7
0

You can do like:

def subString(s):
    for i in range(len(s)):
        for j in range(i+1,len(s)+1):
            print(s[i:j])

subString("aashu") a aa aas aash aashu a as ash ashu s sh shu h hu u

Aashutosh jha
  • 552
  • 6
  • 8