11
votes

Comment insérer un espace après une certaine quantité de caractères dans une chaîne à l'aide de Python?

Je dois insérer un espace après une certaine quantité de caractères dans une chaîne. Le texte est une phrase sans espaces et il doit être divisé avec des espaces après tous les n caractères.

Il devrait donc être quelque chose comme ça. P>

def encrypt(string, length):


4 commentaires

Quelqu'un a posé une question presque exactement comme ça ... Stackoverflow.com/Questtions/10055631/...


duplicaté possible: Stackoverflow.com/Questtions/10061008/...


Je suppose que cette question a une différence, je ne suis pas sûr que cela soit assez important.


4 Réponses :


21
votes
'this isar ando msen tenc e'

1 commentaires

Pour être compatible avec Python 3, remplacez xRange par plage



2
votes

en utilisant iTerTools code> recette méroré :

>>> 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 commentaires

merci :) aussi a travaillé !! Je cherchais cela depuis 6 heures!



0
votes
import textwrap
def encrypt(string, length):
      a=textwrap.wrap(string,length)
      return a

0 commentaires

1
votes
import re
(' ').join(re.findall('.{1,4}','thisisarandomsentence'))
'this isar ando msen tenc e'

0 commentaires