How do I insert a space after a certain amount of characters in a string using python?

def encrypt(string, length):
    return ' '.join(string[i:i+length] for i in range(0,len(string),length))

encrypt('thisisarandomsentence',4) gives

'this isar ando msen tenc e'

Using itertools grouper recipe:

>>> from itertools import izip_longest
>>> def grouper(n, iterable, fillvalue=None):
        "Collect data into fixed-length chunks or blocks"
        # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
        args = [iter(iterable)] * n
        return izip_longest(fillvalue=fillvalue, *args)

>>> text = 'thisisarandomsentence'
>>> block = 4
>>> ' '.join(''.join(g) for g in grouper(block, text, ''))
'this isar ando msen tenc e'

Tags:

Python

String