split string every nth character

How to Split String Every Nth Character in Python

Python allows you to do tons of things with strings and lists. Let us say you need to split a string every nth character, in Python. In this article, we will learn how to do this. There are several ways to split string this way.


How to Split String Every Nth Character in Python

Let us say you have the following string.

s = '1234567890'

Let us say you want to split the above string after every 2 characters.

['12','34','56','78','90']

Here are some of the simple ways to do this.

1. Using List Comprehensions

In this method, we use list comprehension and indexes to define a list of substrings.

>>> S = '1234567890'
>>> n = 2
>>> [s[i:i+n] for i in range(0, len(s), n)]
['12', '34', '56', '78', '90']

In the above code, we use range() function with 3 arguments, first one is 0, second one is the length of the input string, and the third one is the step argument which is n. It returns a list as [0, n, 2n, …]. In our list comprehension, we fetch substring of original list s, between i and i+n indexes, where i takes the values 0, n, 2n , … from the output of range() function.

2. Using wrap function

You can also use built-in wrap() function for the same purpose. as shown below.

>>> from textwrap import wrap
>>> s = '1234567890'
>>> wrap(s, 2)
['12', '34', '56', '78', '90']

wrap() function takes two arguments, the input string and n where we need to split s every nth character. It also works if there are odd number of characters. In this case, it will fill the last substring with as many character as are leftover, which happens to be 1 character in our case.

>>> from textwrap import wrap
>>> s = '123456789'
>>> wrap(s, 2)
['12', '34', '56', '78', '9']

3. Using Regular Expressions

You can also use regular expressions for the same purpose as shown below.

>>> import re
>>> re.findall('..','1234567890')
['12', '34', '56', '78', '90']

In the above code, we use 2 consecutive dots to specify a regular expression consisting of 2 characters.

If your original string has odd number of elements, then you can modify the regex to ..? so that the second character is optional.

>>> import re
>>> re.findall('..?', '123456789')
['12', '34', '56', '78', '9']

In this article, we have learnt several ways to split string every nth character in Python. Out of them using wrap() function is the easiest while using regular expressions is the fastest, in case you are using long strings.

Also read:

How to Reverse/Invert Dictionary Mapping in Python
How to Sort List of Tuples By Second Element in Python
How to Get Key With Max Value in Dictionary
How to Configure Python Flask to be Externally Visible
How to Get Difference Between Two Lists in Python

Leave a Reply

Your email address will not be published.