Eugene Alkhouski Eugene Alkhouski - 6 months ago 14
Python Question

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

For example, suppose we have a string:

'abcdefg'


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)
ch1=''
ch2=''
chars_list=[]
while True:
try:
ch1 = ch2 or next(s)
ch2 = next(s)
chars_list.append(ch1 + ch2)
except:
break
return chars_list


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

Answer

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