python 编程求助 急,请各位帮帮忙
怎样才能把这个string"f(x)=x+2-3\nbox=f(2)+2\nbox=f(f(2))+2\nfunc=3+3*4\n"变成:"box=1+2\nbox=0+...
怎样才能把这个string
"f(x)= x + 2-3\nbox = f(2) + 2\nbox = f(f(2)) + 2\nfunc = 3 + 3 * 4\n"变成:
"box = 1 + 2\nbox = 0 + 2\nfunc = 3 + 3 * 4\n"
想了好久还是没想出来。麻烦大家帮帮,感激不尽。
或者告诉我应该怎么写。。。。只要可行就好了 展开
"f(x)= x + 2-3\nbox = f(2) + 2\nbox = f(f(2)) + 2\nfunc = 3 + 3 * 4\n"变成:
"box = 1 + 2\nbox = 0 + 2\nfunc = 3 + 3 * 4\n"
想了好久还是没想出来。麻烦大家帮帮,感激不尽。
或者告诉我应该怎么写。。。。只要可行就好了 展开
展开全部
import re
src = 'f(x)= x + 2 - 3\nbox = f(2) + 2\nbox = f(f(2)) + 2\nfunc = 3 + 3 * 4\n'
des = []
p = re.compile(r'f\(\d+\)')
pro = src.split('\n')
def f(x):
return eval(pro[0].split('=')[1])
def call_f(match):
x = int(re.search(r'\d+', match.group()).group())
return str(f(x))
for line in pro:
if line.startswith('f(x)'):
continue
else:
while p.search(line) is not None:
line = p.sub(call_f, line)
des.append(line)
print '\n'.join(des)
src = 'f(x)= x + 2 - 3\nbox = f(2) + 2\nbox = f(f(2)) + 2\nfunc = 3 + 3 * 4\n'
des = []
p = re.compile(r'f\(\d+\)')
pro = src.split('\n')
def f(x):
return eval(pro[0].split('=')[1])
def call_f(match):
x = int(re.search(r'\d+', match.group()).group())
return str(f(x))
for line in pro:
if line.startswith('f(x)'):
continue
else:
while p.search(line) is not None:
line = p.sub(call_f, line)
des.append(line)
print '\n'.join(des)
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询