-1

I need to split the text into 3 parts, now I have this:

response = "some text"
res = len(response)
part_1 = response[0:res//2]
part_2 = response[res//2:]
print(part_1)
print(part_2)

this code divides the text into 2 parts, but how can I make it divide into 3 parts?

COLDER
  • 29
  • 4
  • you need to define "three parts", if its divided by 3, then in case like length 8, should you have 2, 3, 3 or 3, 2, 3 or 3, 3, 2? – python_user Jan 05 '21 at 13:40
  • whatever you like, I just need to split the text – COLDER Jan 05 '21 at 13:42
  • Does this answer your question? [Split a string to even sized chunks](https://stackoverflow.com/questions/21351275/split-a-string-to-even-sized-chunks) – costaparas Jan 05 '21 at 13:44
  • partially, but I need to split the text exactly through the function in such a way as I have already done – COLDER Jan 05 '21 at 13:48
  • If you understand what this code does, what troubles you when you attempt to modify it to make 3 parts instead? – zvone Jan 05 '21 at 13:49
  • `part = res//3` and `response[ 0*part : 1*part ]` `response[ 1*part : 2*part ]` `response[ 2*part : 3*part ]` or safer `response[ 2*part : ]` – furas Jan 05 '21 at 15:28

1 Answers1

-1

I would do it with a recursive method. Try this:

def split_str(seq, chunk, skip_tail=False):
    lst = []
    if chunk <= len(seq):
        lst.extend([seq[:chunk]])
        lst.extend(split_str(seq[chunk:], chunk, skip_tail))
    elif not skip_tail and seq:
        lst.extend([seq])
    return lst

The answer is returned as a list. If we did:

print(split_str("some text", 3))

We would get a list looking like: ['som', 'e t', 'ext']

If you don't want to include spaces, add `.replace(" ", ""), like this:

print(split_str("some text".replace(" ", ""), 3))

This gives us: ['som', 'ete', 'xt']

Dharman
  • 30,962
  • 25
  • 85
  • 135
The Pilot Dude
  • 2,091
  • 2
  • 6
  • 24