Forum Archive

How do you split/slice list of strings

sodoku

I have a question about a list of strings

Say I got a list like

a=[‘Haloween’, ‘Boom’, ‘hi’, ‘Howl’, ‘if’, ‘ghosts’]

How do you split or slice the strings to make a list like

a=[‘Ha’, ‘lo’, ‘we’, ‘en’, ‘Bo’, ‘om’, ‘hi’, ‘Ho’, ‘wl’, ‘if’, ‘gh’, ‘os’, ‘ts’]

Is this possible to do?

bennr01

[s[i:i+2] for s in a for i in range(0, len(s), 2)]

Replace 2 with chunk length.

sodoku

Cool awesome Thanks this worked I did not know you could use for twice in one line of code

a=[‘Haloween’, ‘Boom’, ‘hi’, ‘Howl’, ‘if’, ‘ghosts’]
B=[s[i:i+2] for s in a for i in range(0, len(s), 2)]
Print(B)
ccc

The reversed pop pop solution...

def two_chars(a):
    s = list(reversed("".join(a)))
    while s:
        yield "".join((s.pop(), s.pop()))

print(list(two_chars(a)))