# s = 'xiaomi9iphone8iphone7',需要在每个手机型号后面加上逗号,变成 s= 'xiaomi9,iphone8,iphone7' import re print(re.sub(r'(?=iphone)',',',s)) # 顺序肯定环视,所确定的位置右边是字符串iPhone,在此位置即可添加逗号
逆序肯定环视
1 2 3 4 5 6
# s = 'Takes Reservations:No Delivery:No Take-out:Yes Accepts Credit Cards:Yes Good for Groups:No' # 需求是要在Yes,和No的后面加上逗号,使之变成 # s = 'Takes Reservations:No, Delivery:No, Take-out:Yes, Accepts Credit Cards:Yes, Good for Groups:No' import re re.sub(r"(?<=(No))(?=(\s+))|(?<=(Yes))(?=(\s+))",',',s) # 逆序肯定环视,所要确定的位左边必须能匹配上No,或者Yes
顺序否定环视
1 2 3 4
# s = '123aaa',将s字符串变成 s='123,a,a,a,' # 分析一下,就是在字符串右侧非数字的位置,添加逗号,即使用顺序否定环视,匹配右侧非数字位置 s = '123aaa' re.sub(r'(?!\d+)',',',s)