You don't need regex here, you can do this easily with zip()
:
>>> s = "hello"
>>> [x + y for x, y in zip(s, s[1:])]
['he', 'el', 'll', 'lo']
Or even a functional approach with map()
:
>>> list(map(lambda x, y: x + y, s, s[1:]))
['he', 'el', 'll', 'lo']
If you want a way to handle any number of adjacent characters, you could try using a sliding window approach, which takes the first n
characters, and pops the first character, and repeats this until no more substrings can be taken.
Here is an example:
from collections import deque
from itertools import islice
def every_n(s, n):
result = []
items = deque(s)
while len(items) >= n:
result.append(''.join(islice(items, 0, n)))
items.popleft()
return result
Which works as follows:
>>> print(every_n('hello', 2))
['he', 'el', 'll', 'lo']
>>> print(every_n('hello', 3))
['hel', 'ell', 'llo']
>>> print(every_n('hello', 4))
['hell', 'ello']
>>> print(every_n('hello', 5))
['hello']