How to Split a String at Every nth Character in Python [10 Ways]

In this Python tutorial, I will explain “How to split a string at every nth character in Python” with 10 different techniques. We will also see some practical, realistic examples for better understanding.

Splitting a string in Python is a text processing or string manipulation process useful in domains like data processing, web development, and text analytics.

During my research, I found 10 different ways to split a string at every nth character in Python

  1. Using for loop
  2. using while loop
  3. Using list comprehension
  4. using regular expression
  5. Using zip_longest
  6. Using Textwrap
  7. using list+map+join+zip
  8. Using islice from Itertools
  9. Using sliced
  10. Using Recursion with slicing

Let’s see how we can use these methods to split a string at every nth character in Python.

How to split a string at every nth character in Python using the for loop

A for loop in Python is used to iterate over a collection until a given range. We’re using a for loop to split the string into chunks of n characters in Python.

Here is a Python example of splitting the string using a for loop.

Code:

text = "The USA is a diverse and vibrant country."
split_chunks = []
n  = 7
for index in range(0, len(text), n):
    split_chunks.append(text[index : index + n])
print(split_chunks)

We use the string slicing method to split the string and then append the sliced string into a list with the help of the append() function in the Python list.

split_chunks.append(text[index : index + n])

This code splits the string text at every nth character (n=7 in this case) using a for loop, resulting in a list of substrings stored in split_chunks. Each substring contains n characters except the last substring.

Output

['The USA', ' is a d', 'iverse ', 'and vib', 'rant co', 'untry.']

Attached are snapshots illustrating the Python code and its output in Visual Studio.

How to split a string at every nth character in Python

Split string at every nth character in Python using a while loop

A while loop in Python is used to execute a code block repeatedly as long as a specified condition is True. It iterates over the string, appending substrings of length n to the data list until the end of the string.

Here is the code to split a string at every nth character in Python using a while loop:

def split_string_while_loop(s, n):
    data = []
    i = 0
    while i < len(s):
        data.append(s[i:i+n])
        i += n
    return data

string = "Washington DC is the capital of the United States of America"
n = 5
result = split_string_while_loop(string, n)
print(result)

Output: The technique is the same as the above method:

['Washi', 'ngton', ' DC i', 's the', ' capi', 'tal o', 'f the', ' Unit', 'ed St', 'ates ', 'of Am', 'erica']

Here’s a combined view of the Python script and its output within Visual Studio.

Python Split String Every “N” Characters

Split a String into Characters in Python Using List Comprehension

List comprehension is a concise and powerful way to create lists in Python. We will use list comprehension to split a string so it will generate a list of substrings by a given “n” number of characters.

READ:  How to Fix Invalid Syntax in Python

Code

text = "New York City is one of the most populous city in USA."
n = 6
out = [(text[i:i+n]) for i in range(0, len(text), n)]
print(out)

In this example, we are splitting the string text into chunks of n characters (n=6) using list comprehension in Python.

This generates a list of substrings, each containing n characters in Python, by iterating over the range of indices and extracting substrings of length n from the original string.

Output

['New Yo', 'rk Cit', 'y is o', 'ne of ', 'the mo', 'st pop', 'ulous ', 'city i', 'n USA.']

Displayed below is the Python code alongside its output, captured in Visual Studio.

Split string at every nth character in python

Python Split multiple characters from a string using regular expression

Regular expressions(regex) are powerful tools for pattern matching and text processing in Python. We use the re.findall() function to search for all occurrences of a pattern within a string and return a list of matching substrings.

Let’s see an example to split a string at every nth character in Python using re module:

import re
def split_string_regex(s, n):
    return re.findall('.{1,%d}' % n, s)

string = "Los Angeles is a city in California, USA"
n = 5
result = split_string_regex(string, n)
print(result)

Using regular expressions, this code splits the string into chunks of n characters(n=5). It utilizes the re.findall() function in Python to find all substrings matching the regex pattern.

return re.findall('.{1,%d}' % n, s)

{1,%d} matches any character occurring between 1 and n times. The result is a list of substrings, each containing n characters, extracted from the original string.

Output:

['Los A', 'ngele', 's is ', 'a cit', 'y in ', 'Calif', 'ornia', ', USA']

Presented is a composite image showcasing both the Python code and its output in Visual Studio.

How to split a string with N characters in Python

Split a string at every nth occurrence using zip_longest

The zip_longest is a function from the itertools module in Python that combines multiple iterables into tuples.

It takes an iterable (the string), divides it into chunks of length n, and fills any missing characters in the last chunk with a specified fill value

READ:  Python Program to convert String to a List

Here is an instance to split a string at every nth character in Python using the zip_longest function:

from itertools import zip_longest
def fun(n, i, value=None):
    args = [iter(i)] * n
    return zip_longest(fillvalue=value, *args)
my_string = "California is a major hub for technology companies."
n = 8
op_str = [''.join(l) for l in fun(n, my_string, '')]
op = []
for a in op_str:
    op.append(a)
print(op)

Output

['Californ', 'ia is a ', 'major hu', 'b for te', 'chnology', ' compani', 'es.']

Shown below is a combined screenshot of the Python script and its output in Visual Studio.

Python Split string in groups of n consecutive characters

Python Split string in groups of n consecutive characters using Textwrap

The textwrap is a Python module that provides functions for wrapping and formatting text. The wrap() function from the textwrap module is used to split a string into multiple lines of equal length.

If possible, we are using it to divide the string into lines containing n characters by wrapping the text at word boundaries.

Code:

from textwrap import wrap
s = "Texas is the second-largest by both area and population."
n = 5
print(wrap(s, n))

The result is a list of substrings containing n consecutive characters extracted from the original string.

Output

['Texas', 'is', 'the s', 'econd', '-larg', 'est', 'by', 'both', 'area', 'and p', 'opula', 'tion.']

Here is a Screenshot of the example using Visual Studio code editor

Split String Every “N” Characters in python

Splitting a Python String into n Characters using list+map+join+zip

This approach combines several built-in functions and features of Python to split a string into a group of n characters.

We’re using the zip() method to group the elements from each iterator into tuples of length n. Then map(”.join, …) to apply the join() function to each tuple, concatenating the characters into strings.

Here is the example to split a string at every nth character in Python:

s = "The Statue of Liberty is a symbol of freedom and democracy in the United States."
n = 10
print(list(map(''.join, zip(*[iter(s)]*n))))

I combine zip, map, join, and list comprehension in this example. It creates an iterator over the string, groups characters into tuples of length n, joins each tuple into a string, and finally converts the result into a list of substrings.

Output:

['The Statue', ' of Libert', 'y is a sym', 'bol of fre', 'edom and d', 'emocracy i', 'n the Unit', 'ed States.']

Attached is a visual representation of the Python code and its output within Visual Studio.

Python Split multiple characters from string

How to split a string with N characters in Python using the islice function

The islice function in Python stands for “iterable slice”. It allows you to efficiently slice and iterate over elements of an iterable (such as a list, tuple, or string) without creating unnecessary intermediate sequences.

Code:

from itertools import islice
famouse_place = "The Grand Canyon is one of the natural wonders of the world."
n = 8
def split_fun(n, iterable):
    i = iter(iterable)
    piece = list(islice(i, n))
    while piece:
        yield ''.join(piece)
        piece = list(islice(i, n))
print(list(split_fun(n, list(famouse_place))))

In the code, we are using iter() to create an iterator over the string (famouse_place), and then we’re using islice() to create an iterator that yields elements from the input iterator up to the specified value of n.

READ:  Python Array | Python Array Update [With Examples]

And then, list(islice(i, n)) generates a list of N consecutive characters from the input iterator.

Output

['The Gran', 'd Canyon', ' is one ', 'of the n', 'atural w', 'onders o', 'f the wo', 'rld.']

Here is a snapshot featuring the Python script and the resulting output within Visual Studio.

Splitting a Python String into n Characters

How to split a string by an unknown number of characters using sliced

The sliced() function is a built-in method of the more_itertools module of Python, which you have to install separately using:

pip install more_itertools

It allows you to split an iterable into chunks of a specified size, even if the total length of the iterable is not evenly divisible by the chunk size.

Code

from more_itertools import sliced
def split_string_with_sliced(s, n):
    return list(sliced(s, n))

string = "The White House is workplace of the President of the USA."
n = int(input("Enter Split Range: "))
result = split_string_with_sliced(string, n)
print(result)

It returns a list of substrings, each containing n characters, extracted from the original string. The sliced function handles cases where the total length of the string is not evenly divisible by n, ensuring that all characters are included in the output.

Output

['The Whi', 'te Hous', 'e is wo', 'rkplace', ' of the', ' Presid', 'ent of ', 'the USA', '.']

Here is a Screenshot of the example using Visual Studio code editor

Split a String into Characters in Python

Python split string by n number of characters with Recursion with slicing

Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem in Python.

It’s not a preferable approach to use Recursion for this task because it will take more time to execute compared to other techniques we’ve covered.

Here is an instance to split a string at every nth character in Python using recursion.

def split_string_recursive(s, n):
    if len(s) <= n:
        return [s] if s else []
    else:
        return [s[:n]] + split_string_recursive(s[n:], n)
# Example usage:
string = "The Empire State Building is a famous landmark in New York City."
n = 10
result = split_string_recursive(string, n)
print(result)

Output

['The Empire', ' State Bui', 'lding is a', ' famous la', 'ndmark in ', 'New York C', 'ity.']

Displayed below is the Python code and its output, captured in Visual Studio

Python split string by n number of letters

Conclusion

Here, we explored various techniques to split a string at every nth character in Python. We delved into 10 different methods, each offering its approach to achieve this task efficiently.

We covered many possibilities, from simple iterations with for and while loops to more advanced methods like list comprehension, regular expressions, and recursion with slicing.

You can choose the most suitable method based on your requirements and preferences.

You may also like to read these articles on Python: