In this post we will be creating a Python script that will split an existing string every Nth character. To do this we will be using the ‘re’ module which provides regular expression matching operations.
See the string below which for this example we are wanting to split every two characters. The string itself contains ten characters and so each character will fit in to a split.
string = "1234567890"
See the snippet of code below that will split our string every two characters, this is done using the ‘.’ (dot) which represents any single character except a newline
import re string = "1234567890" split = re.findall('..',string) print(split)
This would output the following.
['12', '34', '56', '78', '90'] >>>
A problem arises with the above script where a string has an odd number of characters as the last character will always be excluded. To cater for an odd number of characters refer to the snippet of code below.
Here our string has one character removed leaving a total of nine characters.
import re string = "123456789" split = re.findall('..?',string) print(split)
The above would output the following.
['12', '34', '56', '78', '9'] >>>
Although the Nth character in this example has been two, you may change your code to split a string at a different number.
Take a look at some of our other content around the Python programming language by clicking here.