Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string every n characters but without splitting a word [duplicate]

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?

like image 904
Outcast Avatar asked Jun 18 '19 16:06

Outcast


People also ask

How do I split all characters in a string?

Using the String#substring Method Another way to split a String object at every nth character is to use the substring method. As shown above, the substring method allows us to get the part of the string between the current index i and i+n.


Video Answer


1 Answers

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']
like image 137
Andrej Kesely Avatar answered Oct 18 '22 22:10

Andrej Kesely