How To Split A String Into Fixed Size Chunks In Python

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)

Output:

['Learn', 'share', 'IT']

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)

Output:

['Learn', 'share', 'IT']

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)

Output:

['Learn', 'share', 'IT']

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.

Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *