Python split string by character count | Example code

Use 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

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:

Python split string by character count

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 and suggestions on this Pytho string split topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.