Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string into N equal parts? [duplicate]

Tags:

python

I have a string I would like to split into N equal parts.

For example, imagine I had a string with length 128 and I want to split it in to 4 chunks of length 32 each; i.e., first 32 chars, then the second 32 and so on.

How can I do this?

like image 980
Mo. Avatar asked Mar 21 '14 23:03

Mo.


People also ask

How do you split a string into parts in Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do I split a string into multiple strings?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.


2 Answers

import textwrap print(textwrap.wrap("123456789", 2)) #prints ['12', '34', '56', '78', '9'] 

Note: be careful with whitespace etc - this may or may not be what you want.

"""Wrap a single paragraph of text, returning a list of wrapped lines.      Reformat the single paragraph in 'text' so it fits in lines of no     more than 'width' columns, and return a list of wrapped lines.  By     default, tabs in 'text' are expanded with string.expandtabs(), and     all other whitespace characters (including newline) are converted to     space.  See TextWrapper class for available keyword args to customize     wrapping behaviour.     """ 
like image 60
robert king Avatar answered Sep 30 '22 20:09

robert king


You may use a simple loop:

parts = [your_string[i:i+n] for i in range(0, len(your_string), n)] 
like image 41
Tim Zimmermann Avatar answered Sep 30 '22 20:09

Tim Zimmermann