Python split string by number of characters | Example code

Use range() function and slicing notation to split string by a number of characters in Python.

Example split string by number of characters in Python

Simple example code split a string into array every 2 characters 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’]

Do comment if you have any doubts and suggestions on this Python 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.