0

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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 2
    put your results into a list and then print the list at the end `" ".join(my_list)` also, check out `itertools.permutations()`. – JonSG Jun 08 '21 at 00:18
  • Does this answer your question? [How To Get All The Contiguous Substrings Of A String In Python?](https://stackoverflow.com/questions/22469997/how-to-get-all-the-contiguous-substrings-of-a-string-in-python) – DarrylG Jun 08 '21 at 00:34
  • Or you can use `" "` (single space) instead of `""` (empty string). – nobleknight Jun 08 '21 at 06:07

2 Answers2

2

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

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']
leaf_yakitori
  • 2,232
  • 1
  • 9
  • 21