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??
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??
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']
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']