Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string to even sized chunks

Tags:

How would I be able to take a string like 'aaaaaaaaaaaaaaaaaaaaaaa' and split it into 4 length tuples like (aaaa,aaaa,aaaa)

like image 970
TeaAnyOne Avatar asked Jan 25 '14 13:01

TeaAnyOne


People also ask

How do you split a string into chunks in Python?

Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.

How do you divide a string into substrings in equal length Python?

To split a string into chunks of specific length, use List Comprehension with the string. All the chunks will be returned as an array. We can also use a while loop to split a list into chunks of specific length.

How to split a string into chunks of equal size?

For example, splitting a string AAAAABBBBBCCCCC into chunks of size 5 will result into substrings [AAAAA, BBBBB, CCCCC]. 1. Using LINQ We can use LINQ’s Select () method to split a string into substrings of equal size.

How to split an array into chunks in JavaScript?

The function chunkArray takes an array and the desired size of each chunk in its parameters. We need to know how many groups, or chunks, we need if we want to split the array into sets of the desired size. We get that value by dividing the number of elements in the array by the number of elements we want to have in each chunk.

How to split a list into even chunks in Python?

How to Split a List into Even Chunks in Python 1 Introduction. Splitting strings and lists are common programming activities in Python and other languages. ... 2 Split a List Into Even Chunks of N Elements. A list can be split based on the size of the chunk defined. ... 3 Split a List Into a N Even Chunks. ... 4 Conclusion. ...

How to split a string into substrings of equal size in LINQ?

We can use LINQ’s Select () method to split a string into substrings of equal size. The following code example shows how to implement this: 2. Using String.Substring () method


1 Answers

Use textwrap.wrap:

>>> import textwrap >>> s = 'aaaaaaaaaaaaaaaaaaaaaaa' >>> textwrap.wrap(s, 4) ['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa'] 
like image 122
Ashwini Chaudhary Avatar answered Sep 25 '22 22:09

Ashwini Chaudhary