2012-04-09 410 views
7

Necesito insertar un espacio después de cierta cantidad de caracteres en una cadena. El texto es una oración sin espacios y debe dividirse con espacios después de cada n caracteres.¿Cómo puedo insertar un espacio después de cierta cantidad de caracteres en una cadena usando Python?

por lo que debería ser algo como esto.

thisisarandomsentence 

y quiero que vuelva como:

this isar ando msen tenc e 

la función que tengo es:

def encrypt(string, length): 

hay alguna forma de hacer esto en Python?

+0

Alguien hizo una pregunta casi exactamente como esto ... http://stackoverflow.com/questions/10055631/how- do-i-insert-spaces-en-un-string-using-the-range-function/10055656 # 10055656 – jamylak

+0

posible duplicado: http://stackoverflow.com/questions/10055631/how-do-i-insert-spaces -into-una-cadena-usando-th e-range-function –

+0

También esto es similar: http://stackoverflow.com/questions/10061008/generating-all-n-tuples-from-a-string/10061368 – jamylak

Respuesta

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

encrypt('thisisarandomsentence',4) da

'this isar ando msen tenc e' 
+0

¡FUNCIONÓ! ¡Eres fabuloso! gracias – user15697

+0

Para ser compatible con python 3 reemplazar xrange por rango –

1

Usando 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' 
+1

gracias :) también funcionó !! estado buscando esto durante las últimas 6 horas !! – user15697

Cuestiones relacionadas