2012-04-09 17 views
7

Devo inserire uno spazio dopo una certa quantità di caratteri in una stringa. Il testo è una frase senza spazi e deve essere divisa con spazi dopo ogni n caratteri.Come inserire uno spazio dopo una certa quantità di caratteri in una stringa usando python?

quindi dovrebbe essere qualcosa di simile.

thisisarandomsentence 

e voglio che torni come:

this isar ando msen tenc e 

la funzione che ho è:

def encrypt(string, length): 

c'è comunque di fare questo su Python?

+0

Qualcuno ha chiesto una domanda quasi esattamente come questo ... http://stackoverflow.com/questions/10055631/how- do-i-insert-spaces-in-a-string-using-the-range-function/10055656 # 10055656 – jamylak

+0

possibile duplicato: http://stackoverflow.com/questions/10055631/how-do-i-insert-spaces -nel-a-string-con-esimo e-range-function –

+0

Anche questo è un po 'simile: http://stackoverflow.com/questions/10061008/generating-all-n-tuples-from-a-string/10061368 – jamylak

risposta

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

encrypt('thisisarandomsentence',4)

'this isar ando msen tenc e' 
+0

LAVORATO !!! sei fantastico! grazie – user15697

+0

Per essere compatibile con python 3 sostituire xrange per intervallo –

1

Utilizzando 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

grazie :) ha funzionato anche !! ho cercato questo per le ultime 6 ore !! – user15697

Problemi correlati