Python正则表达式:查找相邻字符

0 python regex

我需要得到一个包含字符串中每两个相邻的字符的列表hello,使得

['he', 'el', 'll', 'lo']
Run Code Online (Sandbox Code Playgroud)

我以为我可以这样做

>>>import re
>>>re.findall(r'..', 'hello')
['he', 'll']
Run Code Online (Sandbox Code Playgroud)

这不是我想要的.我需要使用正则表达式获取上面提到的列表

r.o*_*ook 5

好消息!您的问题与此问题完全相同,可为您提供所需的确切正则表达式:

>>> re.findall(r'(?=(\w\w))', 'hello')
['he', 'el', 'll', 'lo']
Run Code Online (Sandbox Code Playgroud)

阅读链接的线程以获得更多逻辑.

原答案:

不需要正则表达式.你可以使用列表理解.

h = 'hello'

a = [h[i:i+2] for i in range(len(h)-1)]
Run Code Online (Sandbox Code Playgroud)

结果:

['he', 'el', 'll', 'lo']
Run Code Online (Sandbox Code Playgroud)

编辑:RoadRunner的zip/map解决方案更加优雅.也就是说,这个解决方案是可扩展的,所以如果你愿意,你可以获得超过2个相邻的字符:

func = lambda my_list, n: [my_list[i:i+n] for i in range(len(my_list)-n+1)]

# OR, as RoadRunner suggested a cleaner read if you don't like lambdas:

def func(my_list, n): return [my_list[i:i+n] for i in range(len(my_list)-n+1)]
Run Code Online (Sandbox Code Playgroud)

这会给你:

>>> func('hello', 2)
['he', 'el', 'll', 'lo']
>>> func('hello', 3)
['hel', 'ell', 'llo']
>>> func('hello', 4)
['hell', 'ello']
Run Code Online (Sandbox Code Playgroud)