Skip to content

Python split string by number of characters | Example code

  • by

Use the range() function and slicing notation to split strings by a number of characters in Python. You have to use a loop to iterate over the string and extract substrings of the desired length.

Example split string by number of characters in Python

A simple example code split a string into an array every 2 characters in Python.

s = 'ABCDEFG'

n = 2
res = [s[i:i + n] for i in range(0, len(s), n)]

print(res)

Output:

Python split string by number of characters

Same example using list comprehension

import math

s = 'ABCDEFG'

chunks, chunk_size = len(s), math.ceil(len(s) / 4)
res = [s[i:i + chunk_size] for i in range(0, chunks, chunk_size)]

print(res)

OR

s = '1234567890'
n = 2
res = [s[i:i+n] for i in range(0, len(s), n)]

print(res)

Using regex

import re

res = re.findall('..', '1234567890')

print(res)

Output: [’12’, ’34’, ’56’, ’78’, ’90’]

Alternative way with example

def split_string_by_length(string, length):
    return [string[i:i+length] for i in range(0, len(string), length)]

# Example usage
string = "HelloWorld"
split_length = 3

result = split_string_by_length(string, split_length)
print(result)

Comment if you have any doubts or suggestions on this Python 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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading