Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
How do you split/slice list of strings
-
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?
-
[s[i:i+2] for s in a for i in range(0, len(s), 2)]
Replace 2 with chunk length.
-
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)
-
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)))