How to Split Strings of a Given Length in Python?

Estimated read time 1 min read

You can split strings of a given length in Python using the textwrap module, which provides a simple and efficient way to split strings into lines of a specified length.

Here is an example of how to split a string into chunks of length 3 using the textwrap module:

import textwrap

string = "hello world"
chunk_size = 3
chunks = textwrap.wrap(string, chunk_size)



['hel', 'lo ', 'wor', 'ld']

In this example, the textwrap.wrap() method takes two arguments: the string to be split and the maximum length of each chunk. The method returns a list of strings, each of which is no longer than the specified length.

You can change the chunk_size variable to split the string into chunks of a different length.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply