>>> line = '1234567890'
>>> n = 2
>>> [line[i:i+n] for i in range(0, len(line), n)]
['12', '34', '56', '78', '90']
Answer from satomacoto on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-divide-string-into-equal-k-chunks
Divide String into Equal K chunks - Python - GeeksforGeeks
July 15, 2025 - If the string cannot be perfectly divided, the last chunk will contain the remaining characters. List comprehension allows for creating a new list by applying an expression to each element in an iterable. It combines the process of looping and conditional filtering into a single, concise line of code. ... list comprehension iterates over the string s with a step size of k (3), creating substrings of length k. Each substring is sliced from the string and added to the list chunks, resulting in chunks of the string: ['abc', 'def', 'ghi', 'j'].
Discussions

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
python - How to split string into chunks at keyword(s), while preserving spacing and conditions of what words to split at? - Stack Overflow
I want to take an input string and split it up into chunks. The splits should occur when we hit a word in city_list (eg. city_list = ['Berlin']), and include the next four words (spaces and special More on stackoverflow.com
๐ŸŒ stackoverflow.com
March 21, 2023
python - How to split a string into different lengthed chunks? - Stack Overflow
In order to format the string properly, I was required to split it into different lengths of chunks. As an example, This is a string - "25c319f75e3fbed5a9f0497750ea12992b30d565", For spli... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Is there a way to split a string into chunks and store in a list python - Stack Overflow
I have a string x = "yfbrtutcfyugytfytfytcfdycfyrcdtrdrcdtreextredydsadyradrydstrdfrdfrrdecrcxhx" and I wanna split the string x into the following list. y = [ "yfbrtutcfyugytfyt& More on stackoverflow.com
๐ŸŒ stackoverflow.com
People also ask

What is the most Pythonic way to split a string into chunks
ANS: Using list comprehension with slicing, like [string[i:i+n] for i in range(0, len(string), n)], is generally considered the most Pythonic and readable approach for straightforward string chunking.
๐ŸŒ
sqlpey.com
sqlpey.com โ€บ python โ€บ python-string-splitting-chunking-text
Python String Splitting: Efficiently Chunking Text - sqlpey
Can I use regular expressions to split strings into variable-sized chunks
ANS: Yes, regular expressions are flexible. You can use patterns like f'.{{1,{n}}}' in re.findall to specify a maximum chunk size, which will adapt to the available characters.
๐ŸŒ
sqlpey.com
sqlpey.com โ€บ python โ€บ python-string-splitting-chunking-text
Python String Splitting: Efficiently Chunking Text - sqlpey
Is there a built-in Python function for splitting strings into segments
ANS: Yes, the textwrap.wrap(text, width) function is a built-in option specifically designed for reformatting text into lines of a specified width, effectively splitting strings into chunks.
๐ŸŒ
sqlpey.com
sqlpey.com โ€บ python โ€บ python-string-splitting-chunking-text
Python String Splitting: Efficiently Chunking Text - sqlpey
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ split a string into chunks every x words
r/learnpython on Reddit: Split a string into chunks every x words
October 4, 2018 -

Heya,

What I'm looking to do is split a text every x-amount of words. For instance, let's say I have a 300 word string and I want to split it into three chunks. Currently, I'm using:

chunks = text.split(' ')[:100]

However, this just splits the first 100 words into one chunk. What would be the best way to either have this loop through the text in a way that gives me a few different lists, or otherwise makes the list elements each 100 words?

Hope this request makes sense. I've search for an answer for this and feel like I might be using the wrong words to describe my problem, which is why I'm yet to find an answer.

๐ŸŒ
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 ... 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)...
Top answer
1 of 8
86

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
19

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.

Find elsewhere
๐ŸŒ
sqlpey
sqlpey.com โ€บ python โ€บ python-string-splitting-chunking-text
Python String Splitting: Efficiently Chunking Text - sqlpey
July 22, 2025 - Creating a custom generator function offers fine-grained control and memory efficiency, especially for large strings. def split_into_chunks(sequence, chunk_size): """A generator to divide a sequence into chunks of a specified size.""" while sequence: yield sequence[:chunk_size] sequence = sequence[chunk_size:] text_data = '1234567890' segment_size = 2 print(list(split_into_chunks(text_data, segment_size))) # Output: ['12', '34', '56', '78', '90']
๐ŸŒ
Medium
medium.com โ€บ @python-javascript-php-html-css โ€บ splitting-python-lists-into-equal-sized-chunks-a174907ed413
Splitting Python Lists into Equal-Sized Chunks
August 24, 2024 - Similar to the list chunking function, split_string function slices the string into substrings of a specified length using list comprehension. This method efficiently iterates over the string, creating a new substring for every increment of ...
๐ŸŒ
Finxter
blog.finxter.com โ€บ python-split-string-by-length
Python | Split String by Length โ€“ Be on the Right Side of Change
def split_len(s, n): def _f(s, n): while s: yield s[:n] s = s[n:] return list(_f(s, n)) text = "threeseveneightfortyfifty" chunks = 5 print(split_len(text, chunks)) # OUTPUT: ['three', 'seven', 'eight', 'forty', 'fifty'] ๐ŸŒŽRecommended Read: Yield Keyword in Python โ€“ A Simple Illustrated Guide
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 75806956 โ€บ how-to-split-string-into-chunks-at-keywords-while-preserving-spacing-and-cond
python - How to split string into chunks at keyword(s), while preserving spacing and conditions of what words to split at? - Stack Overflow
March 21, 2023 - --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-111-4ee705e7672a> in <module> ----> 1 split_by_city4(test2, ['Berlin']) <ipython-input-107-e4e0eb1457fc> in split_by_city4(text, city_list) 17 if not result or result[-1][-1] in ['\r', '\n']: # start a new chunk if it's the first word or the previous word ends with newline character 18 result.append("") ---> 19 if result and result[-1][-1] not in ['\r', '\n']: # add a space to the last chunk if it doesn't end with newline character 20 result[-1] += " " 21 result[-1] += words[i] # add the current word to the last chunk IndexError: string index out of range ... "How to split string into chunks of length n" - I can't understand how this part of the title relates to the question.
๐ŸŒ
py4u
py4u.org โ€บ blog โ€บ python-split-string-into-smaller-chunks-and-assign-a-variable
How to Split a String into Chunks and Assign Each to a Variable in Python (By Length or Delimiter)
Whether you need to split by a specific delimiter (e.g., commas, hyphens) or into fixed-length segments (e.g., every 5 characters), Python offers flexible tools to achieve this. In this guide, weโ€™ll explore two primary methods for splitting strings: Splitting by delimiter (e.g., splitting "2023-10-05" into year, month, day using - as a delimiter). Splitting by length (e.g., splitting "HelloWorld" into 5-character chunks ["Hello", "World"]).
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-split-string-in-groups-of-n-consecutive-characters
Python | Split string in groups of n consecutive characters - GeeksforGeeks
March 23, 2023 - We are given a string, and our task is to split it into a list where each element is an individual character. For example, if the input string is "hello", the output should be ['h', 'e', 'l', 'l', 'o']. Let's discuss various ways to do this in Python.Using list()The simplest way to split a string in
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-string-split-and-join-methods-explained-with-examples
Python String split() and join() Methods โ€“ Explained with Examples
October 18, 2021 - If you'd like to split <string> on the occurrence of the first comma, you can set maxsplit = 1. And setting maxsplit = 1 will leave you with two chunks โ€“ one with the section of <string> before the first comma, and another with the section ...
๐ŸŒ
Real Python
realpython.com โ€บ how-to-split-a-python-list-into-chunks
How to Split a Python List or Iterable Into Chunks โ€“ Real Python
January 27, 2025 - Conversely, the infinite one will continue to produce chunks as long as you keep requesting themโ€”for instance, by calling the built-in next() function on it. In practice, itertools.batched() should be your preferred tool for splitting a Python list into fixed-size chunks.
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ python split a list into evenly sized chunks?
Python Split a list into evenly sized chunks? - Spark By {Examples}
May 31, 2024 - How to split a list into evenly-sized elements in Python? To split the list evenly use methods like slicing, zip(), iter(), numpy.array_split(), list
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ split long string into chunks
r/learnpython on Reddit: Split long string into chunks
August 29, 2022 -

Hello again...
I'm back with another problem that's probably simple to fix but I'm dumb lol. I'm trying to splice a long string of hexadecimals into smaller sections for a better visual output. The problem is it only uses the first 32 characters then just repeats that input to all the strings.How would I get the function to continue onto the next 32 characters until the end of the string? Is there a way to just remove the first section after each passthrough?

Code:

# Raw hex string (512chars | 256bytes | 1byte == 2chars)
# Note: "XX" is supposed to be in printed line 2
raw = '000102030405060708090A0B0C0D0E0FXX0102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F' 
# Converted byte strings (32chars/16bytes per line)
line = []

def hex_extract(s):
    i = 0
    for x in s:
        # Split chunk into 16bytes
        chunk = ([s[i:i+2] for i in range(0, 32, 2)])
        # Append chunk to converted list
        line.append(chunk)
    for x in line:
        # Print all lines (only reprints the first line :sad_face:
        print(f'[{i+1}]\t| ',*line[i], sep=' ', end='\n')
        i += 1

# Call function
hex_extract(raw)