0

I need to make a string 'abcdef' into a list ['ab', 'cd', 'ef'] on python I tried using list() but it returns ['a', 'b', 'c', 'd',' 'e, 'f']

Can anyone help please??

Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44
Hugo Pires
  • 11
  • 2

2 Answers2

2

You can use zip:

s = "abcdef"
[''.join(x) for x in zip(s[::2], s[1::2])]
# ['ab', 'cd', 'ef']

Or

[s[i:i+2] for i in range(0, len(s), 2)]
# ['ab', 'cd', 'ef']
Psidom
  • 209,562
  • 33
  • 339
  • 356
0

If you don't mind an extra function you could use something like this:

def grouper(string, size):
    i = 0
    while i < len(string):
        yield string[i:i+size]
        i += size

This is a generator so you need to collect all parts of it, for example by using list:

>>> list(grouper('abcdef', 3))
['abc', 'def']
>>> list(grouper('abcdef', 2))  # <-- that's what you want.
['ab', 'cd', 'ef']
MSeifert
  • 145,886
  • 38
  • 333
  • 352