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

Question:

I need to insert a space after a certain amount of characters in a string. The text is a sentence with no spaces and it needs to be split with spaces after every n characters.

so it should be something like this.

thisisarandomsentence

and i want it to return as :

this isar ando msen tenc e

the function that I have is:

def encrypt(string, length):

is there anyway to do this on python?

Asked By: user15697

||

Answers:

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'
Answered By: mshsayem

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'
Answered By: jamylak

Consider using the textwrap library (it comes included in python3):

import textwrap
def encrypt(string, length):
      a=textwrap.wrap(string,length)
      return a
Answered By: Divyanshu Garg
import re
(' ').join(re.findall('.{1,4}','thisisarandomsentence'))

‘this isar ando msen tenc e’

Answered By: sparrow
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.