- Python – Split string into specific length chunks
- Sample Code Snippet
- Examples
- 1. Split string into chunks of length 3
- 2. Split string by length
- 3. Split string with 0 chunk length
- 4. Split string into chunks using While loop
- Summary
- Python split string to chunks
- # Table of Contents
- # Split a string into fixed-size chunks using a list comprehension
- # Split a string into fixed-size chunks using a for loop
- # Split a string into fixed-size chunks using a while loop
- # Split a string into fixed-size chunks using wrap()
- # Split a string into fixed-size chunks using re.findall()
- # Additional Resources
- How To Split A String Into Fixed Size Chunks In Python
- Split a string into fixed size chunks in Python
- Using the len() and range() functions
- Using list comprehension
- Using textwrap.wrap() function
- Summary
Python – Split string into specific length chunks
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.
In this tutorial, we shall learn how to split a string into specific length chunks, with the help of well detailed example Python programs.
Sample Code Snippet
Following is a quick code snippet to split a given string str into chunks of specific length n using list comprehension.
n = 3 # chunk length chunks = [str[i:i+n] for i in range(0, len(str), n)]
Examples
1. Split string into chunks of length 3
In this, we will take a string str and split this string into chunks of length 3 using list comprehension.
Python Program
str = 'CarBadBoxNumKeyValRayCppSan' n = 3 chunks = [str[i:i+n] for i in range(0, len(str), n)] print(chunks)
['Car', 'Bad', 'Box', 'Num', 'Key', 'Val', 'Ray', 'Cpp', 'San']
The string is split into a list of strings with each of the string length as specified, i.e., 3. You can try with different length and different string values.
2. Split string by length
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.
Python Program
str = 'Welcome to Python Examples' n = 4 chunks = [str[i:i+n] for i in range(0, len(str), n)] print(chunks)
['Welc', 'ome ', 'to P', 'ytho', 'n Ex', 'ampl', 'es']
3. Split string with 0 chunk length
In this example, we shall test a negative scenario with chink size of 0, and check the output. range() function raises ValueError if zero is given for its third argument.
Python Program
str = 'Welcome to Python Examples' #chunk size n = 0 chunks = [str[i:i+n] for i in range(0, len(str), n)] print(chunks)
Traceback (most recent call last): File "example1.py", line 4, in chunks = [str[i:i+n] for i in range(0, len(str), n)] ValueError: range() arg 3 must not be zero
Chunk length must not be zero, and hence we got a ValueError for range().
4. Split string into chunks using While loop
In this example, we will split string into chunks using Python While Loop.
Python Program
str = 'Welcome to Python Examples' n = 5 chunks = [] i = 0 while i < len(str): if i+n < len(str): chunks.append(str[i:i+n]) else: chunks.append(str[i:len(str)]) i += n print(chunks)
['Welco', 'me to', ' Pyth', 'on Ex', 'ample', 's']
Summary
In this tutorial of Python Examples, we learned how to split string by length in Python with the help of well detailed examples.
Python split string to chunks
Last updated: Jan 29, 2023
Reading time · 4 min
# Table of Contents
# Split a string into fixed-size chunks using a list comprehension
To split a string into fixed-size chunks:
- Iterate over a range object of the string's length with a step.
- Return a string of length N on each iteration.
- Wrap the result in a list comprehension.
Copied!my_str = 'abcdefgh' n = 2 my_list = [my_str[i:i+n] for i in range(0, len(my_str), n)] print(my_list) # 👉️ ['ab', 'cd', 'ef', 'gh']
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.
We used the range class to get a range of indices that represent the first character in each chunk.
Copied!my_str = 'abcdefgh' my_list = [] n = 2 # 👇️ [0, 2, 4, 6] print(list(range(0, len(my_str), n)))
The range class is commonly used for looping a specific number of times in for loops and takes the following parameters:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range will consist of every N numbers from start to stop (defaults to 1 ) |
The syntax for string slicing is my_str[start:stop:step] .
Copied!my_str = 'abcdefgh' n = 2 my_list = [my_str[i:i+n] for i in range(0, len(my_str), n)] print(my_list) # 👉️ ['ab', 'cd', 'ef', 'gh']
On each iteration, we use the start index to get a chunk of the specified length and return the result.
If the string has a length that is an odd number, the last item in the list will contain fewer characters.
Copied!my_str = 'abcdefghi' n = 2 my_list = [my_str[i:i+n] for i in range(0, len(my_str), n)] print(my_list) # 👉️ ['ab', 'cd', 'ef', 'gh', 'i']
Alternatively, you can use a for loop.
# Split a string into fixed-size chunks using a for loop
This is a three-step process:
- Declare a variable that stores an empty list.
- Iterate over a range of the string's length with a step.
- On each iteration, append a string of length N to the list.
Copied!my_str = 'abcdefgh' my_list = [] n = 2 for i in range(0, len(my_str), n): my_list.append(my_str[i:i+n]) print(my_list) # 👉️ ['ab', 'cd', 'ef', 'gh']
The syntax for string slicing is my_str[start:stop:step] .
Note that the start index is inclusive, whereas the stop index is exclusive.
On each iteration, we get the start index from the current item in the range , and calculate the stop index by adding the start index to the desired chunk length.
# Split a string into fixed-size chunks using a while loop
You can also use a while loop to split a string every nth character.
Copied!my_str = 'abcdefghi' my_str_copy = my_str my_list = [] n = 2 while my_str_copy: my_list.append(my_str_copy[:n]) my_str_copy = my_str_copy[n:] # 👇️ ['ab', 'cd', 'ef', 'gh', 'i'] print(my_list)
We declared a second variable that stores the exact same string.
On each iteration in the while loop, we append the first n characters of the copied string to the list and remove the first n characters from the copied string.
Alternatively, you can use the wrap() method.
# Split a string into fixed-size chunks using wrap()
This is a three-step process:
- Import the wrap() method from the textwrap module.
- Pass the string and the max width of each slice to the method.
- The wrap() method will split the string into a list with items of max length N.
Copied!from textwrap import wrap my_str = 'abcdefgh' n = 2 my_list = wrap( my_str, n, drop_whitespace=False, break_on_hyphens=False ) # 👇️ ['ab', 'cd', 'ef', 'gh'] print(my_list)
The textwrap.wrap method will split the string into a list so that every list item is at most N characters long.
We set the drop_whitespace keyword argument to False because the default behavior of the method is to remove whitespace.
# Split a string into fixed-size chunks using re.findall()
You can also use the re.findall() method to split a string into fixed-size chunks.
Copied!import re my_str = 'abcdefgh' my_list = re.findall(r'.', my_str) print(my_list) # 👉️ ['ab', 'cd', 'ef', 'gh'] my_list = re.findall(r'.', my_str) print(my_list) # 👉️ ['abc', 'def']
The re.findall method takes a pattern and a string as arguments and returns a list of strings containing all non-overlapping matches of the pattern in the string.
We passed the length the chunks should have between the curly braces.
However, note that if the string's length is not divisible by n , the rest of the characters get discarded.
Copied!import re my_str = 'abcdefghi' my_list = re.findall(r'.', my_str) print(my_list) # 👉️ ['ab', 'cd', 'ef', 'gh']
The i character is not contained in the list because it is the 9th character and there is no 10th character in the string.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
- Split a String and remove the Whitespace in Python
- Split a String and get First or Last element in Python
- How to Split a string by Tab in Python
- Split a String into a List of Integers in Python
- Split a String into multiple Variables in Python
- Split a String into Text and Number in Python
- How to convert a String to a Tuple in Python
- Split a string with multiple delimiters in Python
- Split a String by Newline characters in Python
- How to Split a string by Whitespace in Python
- How to Split a string on Uppercase Letters in Python
- Split a String, Reverse it and Join it back in Python
- Split a string without removing the delimiter in Python
- Split a String into a List of Characters in Python
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
How To Split A String Into Fixed Size Chunks In Python
As a Python developer, you probably already know how to split a string into a list using the split() function, but what if you were given the task of splitting a string into little pieces based on a specified size? How should this task be solved? So, today we’ll look at how to split a string into fixed size chunks in Python.
Split a string into fixed size chunks in Python
Using the len() and range() functions
To split a string into fixed size chunks, we can use the built-in len() function to calculate the length of the string and the range() function to create a list of numbers that we will use to iterate over the string. You may not be aware that the range() function contains the step parameter that we rarely use; this parameter is especially useful in this case. Simply specify how many characters you want to merge into a chunk for the step parameter. For example, if we have the string “ LearnshareIT ” and want to split it into 5 character chunks, we can do it as follows:
string = 'LearnshareIT' step = 5 # Create an empty list result = [] # Split the string into a list of 5 character chunks using len() and range() for i in range(0, len(string), step): # Cut the string from position i to i + step and add to the result result.append(string[i:i+step]) print(result)
As you can see, this will print out the string in chunks of 5 characters each. Note that if the original string is not evenly divisible by the desired chunk size, the final element in the list will be shorter than the others.
Using list comprehension
This way is similar to the way above, except that using list comprehension, we don’t need to create an empty list and then push the elements into it. Simply loop over the range of the given string with a list comprehension and get the string using the syntax: string[i:i+step] , as seen in the example above. Like this:
string = 'LearnshareIT' step = 5 # Quickly split a string into chunks using list comprehension result = [string[i:i+step] for i in range(0, len(string), step)] print(result)
Using textwrap.wrap() function
The textwrap module includes several useful functions, one of which is especially handy for splitting strings into fixed size chunks: wrap() . This function takes two arguments: the string to be split and the desired chunk width.
Remember to add the following line of code at the top of your Python file to import the textwrap module before using the wrap() function:
from textwrap import wrap
wrap() has one advantage over the previous two ways: it ignores spaces in your string. Hence the return value of wrap() will never contain spaces. Look at the example below to see how to use wrap() .
from textwrap import wrap # Create a string with lots of spaces in between. string = 'Learn share IT' width = 5 # Easily split the string into chunks with the wrap() function result = wrap(string, width) print(result)
Summary
We have shown you three simple methods to split a string into fixed size chunks in Python. Use list comprehension if you don’t want to import anything into your project, and wrap() if you want your code to be simple and easy to understand. So it is up to you to choose the one that best suits your needs.
Maybe you are interested:
Hi, I’m Cora Lopez. I have a passion for teaching programming languages such as Python, Java, Php, Javascript … I’m creating the free python course online. I hope this helps you in your learning journey.
Name of the university: HCMUE
Major: IT
Programming Languages: HTML/CSS/Javascript, PHP/sql/laravel, Python, Java