re模块的函数-sub()
sub(pattern, repl, string, count=0, flags=0)
替换函数,将正则表达式 pattern 匹配到的全部字符串替换为 repl 指定的字符串,
参数 count 用于指定最大替换次数.
4 import fileinput,re 5 str01='[x=2] [y=2] The sum of [x] and [y] is [x+y]' 6 field_pat = re.compile(r'\[(.+?)\]') 7 scope={} 8 def replacement(match): 9 code=match.group(1) 10 try: 11 return str(eval(code,scope))#处理[x],[y],[x+y] 12 except SyntaxError: 13 exec code in scope #处理[x=2],[y=2]. 14 return '' 15 16 ##lines = [] 17 ##for line in fileinput.input('test.txt'): 18 ## lines.append(line) 19 ## text=''.join(lines) 20 print(field_pat.sub(replacement,str01))
------山的那一边

浙公网安备 33010602011771号