How to insert a space after a certain number of characters in a string using python?

I need to insert a space after a certain number of characters per line. The text is a sentence without spaces, and it must be separated by spaces after each n characters.

therefore there must be something like this.

thisisarandomsentence 

and I want it to return as:

 this isar ando msen tenc e 

function that I have:

 def encrypt(string, length): 

Is there any way to do this in python?

+7
source share
2 answers
 def encrypt(string, length): return ' '.join(string[i:i+length] for i in xrange(0,len(string),length)) 

encrypt('thisisarandomsentence',4) gives

 'this isar ando msen tenc e' 
+11
source

Using itertools perch 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' 
+1
source

All Articles