0

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.

5
  • 1
    What have you tried so far? Please share your code. Commented May 24, 2020 at 22:52
  • 2
    So there cannot be ac? Thats kinda important Commented May 24, 2020 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]) Commented May 24, 2020 at 22:54
  • 2
    Check out print substrings given string Commented May 24, 2020 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? Commented May 24, 2020 at 22:58

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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']

1 Comment

“ac” shouldn’t be on the list
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']

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.