2

I would like to know how to slice my Python string every nth character/letter (in my case the 5th character/letter).

So I have this string "ilikestackoverflow" and I would like for the output to be "ilike stack overf low".

Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
iabestever
  • 25
  • 1
  • 6

2 Answers2

4
 x = zip(*[iter(my_array)]*5)

is a cool but hard to read way of doing it

typically it is done with a list comprehension though

n = 5
x = [my_array[i:i+n] for i in range(0,len(my_array),n)]

this post explains the iter answer best http://www.stavros.io/posts/brilliant-or-insane-code/

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1

What about a good-ol' regular expression?

>>> string = "Ireallylovemyregularexpressions!"
>>> print re.sub(r'(.{5})', r'\1 ', string)
Ireal lylov emyre gular expre ssion s!  

(.{5}) matches every 5 characters, r'\1 ' replaces these 5 characters by the same 5 characters plus a white-space character.


This also works:

>>> m = re.split(r'(.{5})', 'Ilovestackoverflowsobad')
>>> print m
['', 'Ilove', '', 'stack', '', 'overf', '', 'lowso', 'bad']
>>> for word in m:
...     if word == '':
...         pass
...     else:
...         print word,
... 
Ilove stack overf lowso bad
Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63