-1

I'm trying to achieve the next thing. When I put the s as a string such as "Hello", I want it to split for the number in part_length. Meaning that if I put 1 in part_length, the operation result would be: "H e l l o s", if I put 2 in part_length, it would print "He ll os"

This is the code I have now:

def split_in_parts(s, part_length):
    for num in range(part_length):

print(split_in_parts("Hellos", 1))

But I can't figure out how to split the words according to the numbers, which I believe I lack the knowledge in commands. I've tried commands such as ' '.join() but in that case it separates in a way that it is not accordingly to the numbers.

martineau
  • 119,623
  • 25
  • 170
  • 301
godtrianglefd
  • 179
  • 2
  • 12
  • 1
    Split into chunks and then join for example: https://stackoverflow.com/questions/8991506/iterate-an-iterator-by-chunks-of-n-in-python or https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks – pault Nov 24 '20 at 14:27
  • 4
    Does this answer your question? [What is the most "pythonic" way to iterate over a list in chunks?](https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) – Marsroverr Nov 24 '20 at 14:28

3 Answers3

1

Try this method using zip_longest and ' '.join() -

from itertools import zip_longest

def split_in_parts(string, part_length):
    chunk = zip_longest(*[iter(string)]*part_length, fillvalue='')
    return ' '.join([''.join(i) for i in chunk])

print(split_in_parts('hellos', 1))
print(split_in_parts('hellos', 2))
print(split_in_parts('hellos', 3))
h e l l o s
he ll os
hel los
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
0

This is relatively easy with a list comprehension that uses a for loop with a step size of part_length. So first you collect the character groups that you expect, and then you join them together.

def split_in_parts(s: str, part_length: int) -> str:
    char_groups = [s[idx:idx+part_length] for idx in range(0, len(s), part_length)]
    return " ".join(char_groups)
        

print(split_in_parts("Hellos", 2))
# He ll os
Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
0

Since you told you don't know many functions, I tried to keep it as simple as possible. I finally got this

def split_in_parts(s, part_length):
    new_str= ''
    L = []
    for i in s:
        L.append(i)
    while len(L)!=0:
        for i in range(part_length):
            ele = L.pop(L.index(L[0]))
            new_str+=ele
        new_str+=' '
    return new_str
Satyajit
  • 115
  • 9