How would I be able to take a string like 'aaaaaaaaaaaaaaaaaaaaaaa'
and split it into 4 length tuples like (aaaa
,aaaa
,aaaa
)
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.
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.
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.
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 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. ...
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
Use textwrap.wrap
:
>>> import textwrap >>> s = 'aaaaaaaaaaaaaaaaaaaaaaa' >>> textwrap.wrap(s, 4) ['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With