9

Let's suppose that I have this in python:

orig_string = 'I am a string in python'

and if we suppose that I want to split this string every 10 characters but without splitting a word then I want to have this:

strings = ['I am a ', 'string in ', 'python']

or this (without the whitespaces at the splittings):

strings = ['I am a', 'string in', 'python']

Therefore, the split should be done exactly before the word which would have been splitted otherwise at each case.

Otherwise, I would have this:

false_strings = ['I am a str', 'ing in pyt', 'hon']

Just to mention that in my case I want to do this every 15k characters but I gave the example above for every 10 characters so that it could be written in a concise way here.

What is the most efficient way to do this?

Outcast
  • 4,967
  • 5
  • 44
  • 99

1 Answers1

9

You can use built-in textwrap.wrap function (doc):

orig_string = 'I am a string in python'

from textwrap import wrap

print(wrap(orig_string, 10))

Prints:

['I am a', 'string in', 'python']
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 4
    when 2 people have already suggested this in the comments is it good *etiquette* to write an answer? – Chris_Rands Jun 18 '19 at 17:09
  • I didn't check the comments. It just popped up from my head (because I use it casi every day) – Andrej Kesely Jun 18 '19 at 17:10
  • 1
    I wrote it in comments because I can't write a full answer right now. So it's ok for me – Olivier Melançon Jun 18 '19 at 17:11
  • @OlivierMelançon yah i don't have a strong view, i'd probably make the answer "community wiki" in this case – Chris_Rands Jun 18 '19 at 17:12
  • 2
    I ready don't mind as long as we end up with a quality answer on top – Olivier Melançon Jun 18 '19 at 17:14
  • 4
    @Chris_Rands I don't think this is a misstep in *etiquette*. Answers belong in the answer section where they can be voted on and selected. – Mark Jun 18 '19 at 17:15
  • @Chris_Rands: It's very important to post answers as actual answers, even if comments may have already mentioned them. I came here via the search engine. Both SO and Google search engines will only find questions and answers, they ignore comments. If you search on `[python] split n characters textwrap` it'll find the answer. (The etiquette of which user deserves rep is separate issue.) – smci Jan 03 '20 at 13:46