-1

Lets say I have a string...

mystr = "abcdefghij"

I want to split it so that it becomes a list in groups of two like so...

mylist = ['ab', 'cd', 'ef', 'gh', 'ij']

I know there is a list() method that will separate every character and a split() method that will split on a designated character, but I can't figure out how to split it into groups where there is no whitespace or special character to split on.

Am I just missing something within those two methods, or is there a different way to do this?

martineau
  • 119,623
  • 25
  • 170
  • 301
Joshua
  • 103
  • 10
  • Try this: `"abcdefghij"[2:5]` and then build on this example to do whatever it is you want to do (hint: a string in Python is an iterable object). – Aleksander Lidtke Jul 08 '16 at 16:07

1 Answers1

1

Take a look at the grouper recipe in itertools:

https://docs.python.org/2.7/library/itertools.html#recipes

I think that does what you want in a generic way.

SpoonMeiser
  • 19,918
  • 8
  • 50
  • 68