Use the range() function and slice notation to split a string at every character count in Python. We will learn in this tutorial how to write a Python program to split the string by every nth character.
Example split string by character count in Python
A simple example code uses a for-loop and range(start, stop, step) to iterate over a range from start to stop where stop is the len(string) and step is every number of characters where the string will be split
It will also count whitespace as char. It’s a list comprehension example with a more compact implementation.
string = 'ABC XYZ PQRS'
n = 3 # every 3 characters count
res = [string[i:i + n] for i in range(0, len(string), n)]
print(res)
Output:
The same example in for loop way
a_string = "abcde"
res = []
n = 2
for index in range(0, len(a_string), n):
res.append(a_string[index: index + n])
print(res)
Output: [‘ab’, ‘cd’, ‘e’]
Do comment if you have any doubts or suggestions on this Pytho string split topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.