0

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?

Community
  • 1
  • 1
Eugene Alkhouski
  • 550
  • 1
  • 6
  • 12

2 Answers2

4

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']
Delgan
  • 18,571
  • 11
  • 90
  • 141
0

You could try this (hacky) solution:

def str_split(s):
    return [s[start:end] for start, end in enumerate(range(2, len(s)+1))]

Delgan's zipping solution seems more elegant though :)

user2390182
  • 72,016
  • 6
  • 67
  • 89