In this Python tutorial, we will learn to split a string at every nth character. Remember empty spaces are also counted as a character in a string.
Table Of Contents
Method 1 : Using range() function :
First method that we will be using to split a string at every nth character in Python is the range() function. The range() function accepts three parameters which are start, stop, stop.
- start : Optional , default is 0
- stop : Required
- step : Optional
As the name suggests start and stop are used to specify a position from where to start and where to end. Step is provided to to specify the incrementation.
Apart from the range() function, we will also be using for loop to iterate over the string. Also the len() function, to determine length of given string. The len() function takes a string as an argument and returns the length of string. Also we will be using the list.append() method , which inserts the given string at last index of a list.
- Iterate over all characters of a string in a step size of 5.
- During each iteration select next 5 characters as a substring and add that to a list.
See the example code below
- Python: Remove whitespace from the start of string
- Convert a Unicode String to a String in Python
- How to Convert a String to a double in Python?
- Get first character of first String in a List in Python
example_str = "This is a Python Tutorial" splited_str =  n = 5 # looping through example_str from 0 to length # of example_str in a step size of 5 for index in range(0, len(example_str), n): # slicing at iteration stops and storing it in splited_str splited_str.append(example_str[index : index + n]) print(splited_str)
['This ', 'is a ', 'Pytho', 'n Tut', 'orial']
In above example code and output we have succesfully splitted the given string at every nth(5) character. Here we have used for loop to iterate through the example_str. Using the range() function we iterated from 0 to length of example_str in a step size of 5. Then we used index slicing to slice string at every 5th(nth) character and stored it in a list using append() method.
Method 2 : Using List Comprehension
Next method we will be using to split a given string at every nth character is List Comprehension. It has a shorter syntax. It creates a new list based on certain criteria. See the Example Code below.
example_str = "This is a Python Tutorial" # here we will split the string # at every 4th character n = 4 # Storing splitted string from every 4th character # in splited_str through List Comprehension splited_str = [ example_str[index : index + n] for index in range(0, len(example_str), n)] print(splited_str)
['This', ' is ', 'a Py', 'thon', ' Tut', 'oria', 'l']
In above code and output, through the List Comprehension we have successfully splitted the string in example_str variable at every 4th character.
Method 3 : Using wrap() function
Next method that we will be using is the wrap() function of textwrap module. This module comes bundled with Python, and provides some convenience functions, as well as TextWrapper which can be used to just wrapping or filling one or two text strings.
Here we will be using the wrap() function which returns a list divided by a given width (provided as an argument).
It gets two arguments :
- First : string
- Second : width , default width = 70
See the example code below :
from textwrap import wrap example_str = "This is a Python Tutorial" # spliting the string at every 5th character n = 5 # Initialize an empty list to # store splitted string in it splited_str =  # Spliting string at every 5th character # and storing it in splitied_str list splited_str = wrap(example_str,n) print(splited_str)
['This', 'is a ', 'Pytho', 'n Tut', 'orial']
In above example code and output, we have successfully splitted the given string at every 5th character using wrap() function of textwrap module and sotred in splited_str variable.
Method 4 : Using while loop and list slicing
Another method that we can use is a combination of while loop and list slicing. First we will run a while loop until there are chars in the given main string, for that we will re-initialize the main string with the chars which has not been sliced. And then the sliced str will be appended in splited_str variable with append() method. See the example code below.
# example string with no spaces example_str = "123456789012" # Initaialize an empty list splited_str =  # split string at every 4th character n = 4 # looping through the exsmple_str while example_str: # append into splited_str by slicing # example_str at given nth character splited_str.append(example_str[:n]) # reinitialize example_str to residual so # that looping stops if there is nothin in it. example_str = example_str[n:] print(splited_str)
['1234', '5678', '9012']
Again in this method we have used some basics methods of python programming language to split at every nth(here 4th) character. In this method example string which has been used without any spaces.
So in this Python tutorial, four different methods has been used to split string at every nth character in Python programming language. You can always method you want but the most easy to understand or self describing methods are third and fourth one. In first three methods example string has spaces inside and python counts a spcae as a character that’s why in last method a string with no space has been used for better understanding.
Try to run these example codes in your machine , i have used Python 3.10.1 for writing examples. Type python –version to check your python version. Happy Coding.