Eugene Alkhouski Eugene Alkhouski - 2 years ago 118
Python Question

How to split python string every nth-1 + nth char

For example, suppose we have a string:


And we need to get a list like this:

['ab', 'bc', 'cd', 'de', 'ef', 'fg']

we should not use any kind of library

Here is my solution:

def str_split(s):
s = iter(s)
while True:
ch1 = ch2 or next(s)
ch2 = next(s)
chars_list.append(ch1 + ch2)
return chars_list

I wonder is there a better solution? Maybe it is possible to use list comprehension like here?

Answer Source

You can simply use zip() and a list comprehension:

chars_list = [ch1 + ch2 for ch1, ch2 in zip(s, s[1:])]

More generally, if you need a solution for any n:

n = 3
chars_list = [s[i:i+n] for i in range(0, len(s) - n + 1, n - 1)]
# ['abc', 'cde', 'efg']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download