-1

I'm very new to python and was wondering what the most pythonic/easy way is to split a string into a list with parts of N characters.

I've come across this:

>>>s = "foobar"
>>>list(s)
['f', 'o', 'o', 'b', 'a', 'r']

which is how I can turn a string into a list of characters, but what I would want is to have a method that would look like this:

>>>def splitInNSizedParts(s, n):

where

>>>print(splitInNSizedParts('foobar', 2))
['fo', 'ob', 'ar']
martineau
  • 119,623
  • 25
  • 170
  • 301
Julian Declercq
  • 1,536
  • 3
  • 17
  • 32
  • 1
    There are also some good ideas [here](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) and [here](http://stackoverflow.com/questions/9475241/split-python-string-every-nth-character). – Alex Riley Sep 18 '16 at 10:22

1 Answers1

1
import textwrap
print textwrap.wrap("foobar", 2)

Then your function will be :

def splitInNSizedParts(s, n):
     return textwrap.wrap(s, n)
khelili miliana
  • 3,730
  • 2
  • 15
  • 28