就是给字符串的每一个字符前后都确保有.*
key = r'djaskljflkasdfjklfj'
p1 = r'(.)'
p2 = r'(.$)'
newkey = re.sub(p1,r'.*\1',key)
newkey = re.sub(p2,r'\1.*',newkey)
print(newkey)
-->.*d.*j.*a.*s.*k.*l.*j.*f.*l.*k.*a.*s.*d.*f.*j.*k.*l.*f.*j.*
以上我是经过了两次正则匹配,有没有办法一条正则就做到这一点呢
# 不知算不算满足同学需求 import re key = r'djaskljflkasdfjklfj' p1 = r'(.)' p2 = lambda matched:".*"+ matched.group(0) if matched.span()[1] < matched.endpos else ".*"+ matched.group(0) + ".*" new_key = re.sub(p1,p2,key) print(new_key)