Python 字符串内插的实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lanadeus/article/details/84952949

仿照ruby的样式,实现了python字符串内插.

def fill(s):
    import re
    pattern = re.compile(r'#\{(.*)\}')
    func = lambda s: str(eval(s.groups()[0]))
    return re.sub(pattern, func, s)


haha = 2333
print(fill('#{haha + 1}')) #=>2334
ww = range(5)
print(fill('#{list(map(lambda x:x*3+1,ww))}')) #=>[1, 4, 7, 10, 13]

真实闲得蛋疼.不如直接用ruby.

还有,需要注意的是:eval函数不能执行赋值语句. exec函数只能返回None.

猜你喜欢

转载自blog.csdn.net/lanadeus/article/details/84952949