Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

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?

like image 242
user15697 Avatar asked Apr 09 '12 07:04

user15697


2 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'
like image 91
mshsayem Avatar answered Sep 21 '22 08:09

mshsayem


import re
(' ').join(re.findall('.{1,4}','thisisarandomsentence'))

'this isar ando msen tenc e'

like image 25
sparrow Avatar answered Sep 18 '22 08:09

sparrow