>>> x = "qwertyui"
>>> chunks, chunk_size = len(x), len(x)//4
>>> [ x[i:i+chunk_size] for i in range(0, chunks, chunk_size) ]
['qw', 'er', 'ty', 'ui']
Answer from Alexander on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-split-a-string-by-custom-lengths
Python - Split a String by Custom Lengths - GeeksforGeeks
April 17, 2023 - Input : test_str = 'geeksforgeeks', cus_lens = [10, 3] Output : ['geeksforge', 'eks'] Explanation : Strings separated by custom lengths. ... In this, we perform task of slicing to cater custom lengths and loop is used to iterate for all the lengths. ... # Python3 code to demonstrate working of # Multilength String Split # Using loop + slicing # initializing string test_str = 'geeksforgeeks' # printing original string print("The original string is : " + str(test_str)) # initializing length list cus_lens = [5, 3, 2, 3] res = [] strt = 0 for size in cus_lens: # slicing for particular length res.append(test_str[strt : strt + size]) strt += size # printing result print("Strings after splitting : " + str(res))
Discussions

Python Split string in a certain length - Stack Overflow
I have this situation: I got a string that I want to split every X characters. My problem is that the split method only splits the string based on a string such as: a = 'asdeasxdasdqw' print a.spl... More on stackoverflow.com
🌐 stackoverflow.com
May 23, 2017
What's the best way to split a string into fixed length chunks and work with them in Python? - Stack Overflow
I've tried searching various solutions ... of Python just isn't sufficient to get anything to work without doing it in a very long winded way using a tangled mess of if then else statements that's probably going to tie me in knots! ... Try import time and time.sleep for delays. ... To split into chunks, the chunks function here should work. ... @mgilson @Marcin - this question is slightly different if you consider that when the input is a string, you can use ... More on stackoverflow.com
🌐 stackoverflow.com
April 5, 2017
python - How to split strings of different lengths? - Stack Overflow
I'm trying to make my own encryption ... how to split strings that have different lengths into a list. Here is my code: import random from calculations import test_divisibility # This is a function that returns which numbers can divide evenly into the given number def encrypt(text): div_by = ... More on stackoverflow.com
🌐 stackoverflow.com
Split string into a list, with items of equal length in python 3 - Stack Overflow
I'm looking to split a given string into a list with elements of equal length, I have found a code segment that works in versions earlier than python 3 which is the only version I am familiar with. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Finxter
blog.finxter.com › python-split-string-by-length
Python | Split String by Length – Be on the Right Side of Change
Summary: You can split a string by length by slicing the string into chunks of equal lengths.
🌐
TutorialsPoint
tutorialspoint.com › python-program-to-split-a-string-by-custom-lengths
Python Program to Split a String by Custom Lengths
The following program returns a list after splitting the input list by given custom lengths using for loop and slicing - # input string inputString = 'hitutorialspoint' # printing input string print("Input string: ", inputString) # input custom lengths list customLengths = [4, 1, 6, 5] # empty list for storing a resultant list outputList = [] # initializing start index as 0 startIndex = 0 # travsering through each element of the custom lengths list for l in customLengths: # appending the custom length string sliced from the # starting index to the custom length element outputList.append(inputString[startIndex: startIndex + l]) # Increment the start Index value with the custom length element startIndex += l # printing the resultant output list print("Resultant list after splitting by custom lengths:\n", outputList)
🌐
GeeksforGeeks
geeksforgeeks.org › python-split-a-string-by-custom-lengths
Python – Split a String by Custom Lengths | GeeksforGeeks
April 17, 2023 - Input : test_str = 'geeksforgeeks', cus_lens = [10, 3] Output : ['geeksforge', 'eks'] Explanation : Strings separated by custom lengths. ... In this, we perform task of slicing to cater custom lengths and loop is used to iterate for all the lengths. ... # Python3 code to demonstrate working of # Multilength String Split # Using loop + slicing # initializing string test_str = 'geeksforgeeks' # printing original string print("The original string is : " + str(test_str)) # initializing length list cus_lens = [5, 3, 2, 3] res = [] strt = 0 for size in cus_lens: # slicing for particular length res.append(test_str[strt : strt + size]) strt += size # printing result print("Strings after splitting : " + str(res))
🌐
Python Examples
pythonexamples.org › python-split-string-into-specific-length-chunks
Split String into Specific Length Chunks - 3 Python Examples
In this example we will split a string into chunks of length 4. Also, we have taken a string such that its length is not exactly divisible by chunk length. In that case, the last chunk contains characters whose count is less than the chunk size we provided. str = 'Welcome to Python Examples' n = 4 chunks = [str[i:i+n] for i in range(0, len(str), n)] print(chunks)
🌐
NCL
ncl.ucar.edu › Document › Functions › Built-in › str_split_by_length.shtml
str_split_by_length
Splits a string or strings into an array of strings given a length, or an array of lengths. Available in version 6.0.0 and later. function str_split_by_length ( string_val [*] : string, length_val [*] : integer ) return_val [*] : string
Find elsewhere
🌐
ReqBin
reqbin.com › code › python › nxrhfweu › python-split-string-example
How do I split a string in Python?
December 20, 2022 - Regular expressions are more ... Since strings in Python are an array of bytes, you can use the range operator to take a range of characters from a string, just like you do for collections....
Top answer
1 of 8
84

One solution would be to use this function:

def chunkstring(string, length):
    return (string[0+i:length+i] for i in range(0, len(string), length))

This function returns a generator, using a generator comprehension. The generator returns the string sliced, from 0 + a multiple of the length of the chunks, to the length of the chunks + a multiple of the length of the chunks.

You can iterate over the generator like a list, tuple or string - for i in chunkstring(s,n): , or convert it into a list (for instance) with list(generator). Generators are more memory efficient than lists because they generator their elements as they are needed, not all at once, however they lack certain features like indexing.

This generator also contains any smaller chunk at the end:

>>> list(chunkstring("abcdefghijklmnopqrstuvwxyz", 5))
['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy', 'z']

Example usage:

text = """This is the first line.
           This is the second line.
           The line below is true.
           The line above is false.
           A short line.
           A very very very very very very very very very long line.
           A self-referential line.
           The last line.
        """

lines = (i.strip() for i in text.splitlines())

for line in lines:
    for chunk in chunkstring(line, 16):
        print(chunk)
2 of 8
15

The standard library offers textwrap.wrap:

from textwrap import wrap

s = "some random text that should be splitted into chunks"

print(wrap(s, width=3))

['som', 'e r', 'and', 'om ', 'tex', 't t', 'hat', 'sho', 'uld', 'be ', 'spl', 
 'itt', 'ed ', 'int', 'o c', 'hun', 'ks']

Note: the underlying TextWrapper is designed to split text (as in a sentence), not arbitrary sequences of characters. The result is not guaranteed to be a sequence of strings with length == width.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-divide-string-into-equal-k-chunks
Divide String into Equal K chunks - Python - GeeksforGeeks
July 15, 2025 - textwrap.wrap() function splits the s into substrings of a specified maximum width (k). It returns a list of these substrings, each having a length of up to k characters. ... It returns a list chunks containing the wrapped substrings, resulting ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-split-given-string-into-equal-halves
Python | Split given string into equal halves - GeeksforGeeks
July 12, 2025 - s1 = "GeeksforGeeks" # Use string ... + len(s1)%2:]: Extracts the second half, starting from the midpoint. divmod() function divides the string length by 2, obtaining the quotient (length of the first part) and remaind...
🌐
University of Pittsburgh
sites.pitt.edu › ~naraehan › python3 › split_join.html
Python 3 Notes: Split and Join
Python 3 Notes [ HOME | LING 1330/2330 ] Splitting and Joining Strings <<Previous Note Next Note >> On this page: .split(), .join(), and list(). Splitting a Sentence into Words: .split() Below, mary is a single string. Even though it is a sentence, the words are not represented as discreet units.
Top answer
1 of 2
2

Here's a function that will break a string into c equal size chunks, with the last chunk containing any overflow:

def split_str(strng, c):
    l = len(strng) // c
    r = [strng[n * l:(n + 1) * l] for n in range(c - 1)]
    r.append(strng[(c - 1) * l:])
    return r

s = 'Now is the time for all good men to come to the aid'

print(split_str(s, 4))

Result:

['Now is the t', 'ime for all ', 'good men to ', 'come to the aid']

You can simplify the function a bit if you know that the string will always divide evenly. Then it would be just:

def split_str(str, c):
    l = len(str) // c
    r = [str[n*l:(n+1)*l] for n in range(c)]

The rest is just math, which it sounds like you already have a handle on. Or do you need help finding the factors of a number? I know there are lots of questions about that already on SO.

2 of 2
0

Here's something a little different that will break the string into as many equally- sized groups as possible and put any excess into an extra one. That won't happen when the length if the string is an exact multiple of the group size.

from itertools import zip_longest

_filler = object()  # Value which couldn't be in data.

def grouper(n, iterable):
    for result in zip_longest(*[iter(iterable)]*n, fillvalue=_filler):
        yield tuple(v for v in result if v is not _filler)

n = 4
s = 'Now is the time for all good men to come to the aid'
group_len = len(s) // n
result = list(''.join(group) for group in grouper(group_len, s))
print(result)

Output

['Now is the t', 'ime for all ', 'good men to ', 'come to the ', 'aid']
🌐
ActiveState
code.activestate.com › recipes › 496784-split-string-into-n-size-pieces
Split String into n-size pieces « Python recipes « ActiveState Code
June 6, 2006 - It seems like there should be a ... for any sequences that support slicing and len() (thus including lists): def split_len(seq, length): return [seq[i:i+length] for i in range(0, len(seq), length)]...
🌐
Upgrad
upgrad.com › home › blog › data science › python split() function: syntax, parameters, examples
Python Split() Function: Examples, Methods & Practical Tips
July 6, 2026 - Note the first empty string is due to the leading /. ... Now that we understand what does split function do in python and its parameters, let's look at some real-world scenarios where it is incredibly useful. Imagine you have a text file (data.csv) with the following content: name,age,city Alice,30,New York Bob,25,Los Angeles · You can read this file line by line and use split(',') to process each record.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-string-split
Python String Split() Method | DigitalOcean
April 17, 2024 - Finally, let’s look at a real-life example where the user will enter the CSV data and we will split it into the list of strings. input_csv = input('Please enter CSV Data\n') input_csv_split_list = input_csv.split(sep=',') print('Input Data Length =', len(input_csv_split_list)) print('List of inputs =', input_csv_split_list) ... Please enter CSV Data Java,Android,Python,iOS,jQuery Input Data Length = 5 List of inputs = ['Java', 'Android', 'Python', 'iOS', 'jQuery']