Huy Huynh
Huy Huynh

Reputation: 1

How do you separate all possible substrings in a string?

For example lets say:

Str = "abc"

The desired output I am looking for is:

a, b, c, ab, bc, abc

so far I have:

#input
Str = input("Please enter a word: ")
#len of word
n = len(Str)
#while loop to seperate the string into substrings
for Len in range(1,n + 1):
   for i in range(n - Len + 1):
      j = i + Len - 1
      for k in range(i,j + 1):
          #printing all the substrings
          print(Str[k],end="")

this would get me:

abcabbcabc

which has all the correct substrings but not seperated. What do I do to get my desired output? I would think the end='' would do the trick in seperating each substring into each individual lines but it doesn't. Any suggestions?

Upvotes: 0

Views: 85

Answers (2)

leaf_soba
leaf_soba

Reputation: 2518

a more pythonic solution

code:

import itertools
s = "abc"
for i in range(1,len(s)+1):
    print(["".join(word) for word in list(itertools.combinations(s,i))])

result:

['a', 'b', 'c']
['ab', 'ac', 'bc']
['abc']

Upvotes: 0

wjandrea
wjandrea

Reputation: 33145

You could add an extra print() in the i loop, but it's easier to use a slice instead:

s = "abc"
n = len(s)
for size in range(1, n+1):
    for start in range(n-size+1):
        stop = start + size
        print(s[start:stop])

Output:

a
b
c
ab
bc
abc

On the other hand, if you want them literally joined on comma-spaces as you wrote, the simplest way is to save them in a list then join at the end.

s = "abc"
n = len(s)
L = []
for size in range(1, n+1):
    for start in range(n-size+1):
        stop = start + size
        L.append(s[start:stop])
print(*L, sep=', ')

Or, I would probably use a list comprehension for this:

s = "abc"
n = len(s)
L = [s[j:j+i] for i in range(1, n+1) for j in range(n-i+1)]
print(*L, sep=', ')

Output:

a, b, c, ab, bc, abc

Upvotes: 2

Related Questions