目的: 给表达式 '10+6/5-4*2' 中每个运算符左右都加一个空格字符,变成:'10 + 6 / 5 - 4 * 2'
思路: 分组、捕获、替换
1. 替换字符中含参数 1 (此处不能叫参数,想不到叫什么,那就不管它~~)
>>> bds = '10+6/5-4*2' # 表达式 >>> m = re.sub(r'([*+-/])', ' 1 ', bds) # 注意1左右皆有一个空格!! >>> m '10 + 6 / 5 - 4 * 2'
2. 替换字符中含参数 g<1>
>>> bds = '10+6/5-4*2' # 表达式 >>> m = re.sub(r'([*+-/])', ' g<1> ', bds) >>> m '10 + 6 / 5 - 4 * 2'
3. 模式中也可含参数 1
>>> greed = "Hello Jack! Are you OK, Jack?" >>> m = re.sub(r"Hello (w+)! Are you OK, 1?", "g<1>", greed) >>> m "Hello Jack! Are you OK, Jack?"
4. 模式中也可含参数 :命名组 (?P=yourname)
>>> greed = "Hello Jack! Are you OK, Jack?" >>> m = re.sub(r"Hello (?P<yourname>w+)! Are you OK, (?P=yourname)?", "g<yourname>", greed) >>> m "Hello Jack! Are you OK, Jack?"