In this article, we will see efficient ways to split a string by length in Python.

There are multiple ways to split a string by length in python, from those different ways, which one to use is depends upon the requirement and use case.

For example, if we have the smaller datasets then we can use list comprehensions and textwrap module to split the string by length easily. Whereas when datasets are large it is always recommended to use the generator functions which are useful when we want to generate a large sequence of values but do not want to store them all in memory simultaneously.

Let us discuss all the three ways of splitting a string by the length

1. List comprehension is a easiest way to create lists in Python. We can use list comprehension to split a string by length in an efficient and readable manner.

Here is an example:

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

input_string = "PythonIsAwesome"
chunk_length = 3
chunks = split_string_by_length(input_string, chunk_length)
print(chunks)

Output

['Pyt', 'hon', 'IsA', 'wes', 'ome']

In the above example we used the function split_string_by_length which is used to iterate through the input string from the start to the end, with a step size equal to the desired chunk length. For each step, we slice the string from the current index to the current index plus the chunk length which splits the string into smaller parts of the specified length.

2. We can also use the textwrap.wrap function in the textwrap module to efficiently split a string by length.

The text.wrap function splits the string into multiple parts of the specified length efficiently.

Following is the example

import textwrap

def split_string_by_length(s, length):
    return textwrap.wrap(s, length)

input_string = "PythonIsAwesome"
chunk_length = 3
chunks = split_string_by_length(input_string, chunk_length)
print(chunks)

Output

['Pyt', 'hon', 'IsA', 'wes', 'ome']

3. By using the Generator function we can split the string into multiple parts in an efficient manner. This is really very useful when we are working with the large datasets.

Here is an example:

def split_string_by_length(s, length):
    for i in range(0, len(s), length):
        yield s[i:i + length]

input_string = "PythonIsAwesome"
chunk_length = 3
chunks = list(split_string_by_length(input_string, chunk_length))
print(chunks)

In the split_string_by_length function, we use a generator function to traverse the input string from beginning to end, with each step corresponding to the desired chunk length. We return the string slice from the current index to the current index plus the chunk length at each step.

Categorized in:

Tagged in: