import re
r = re.compile("#{([^}]*)}")
def I(string):
def eval_str_match(m):
return str(eval(m.group(1)))
return r.sub(eval_str_match,string)
*除了python味道/风格/标准
是否有一种更简洁的方式来称它为单字母方法?
正则表达式有什么可以错过的吗?
我应该使用repr而不是str?
我知道eval可能很危险但我不明白为什么
I("#{some_func()}\n")
更糟糕的是
"%s\n" % str(some_func())
答案 0 :(得分:2)
不确定你想要完成什么,但这有用吗?
I = '{}\n'.format
I(some_func())
或
def I(func):
return "%x\n" % func()
I(some_func())
使用评论中的示例
I([x*2 for x in [1,2,3]])
工作正常(虽然我不知道你希望输出看起来像什么),就像
一样I(''.join((self.name, ' has ', self.number_of_children)))
但你真的应该这样做
'{} has {}'.format(self.name, self.number_of_children)
仍然是一行。
答案 1 :(得分:1)
这就是我想出来的。
my_print.py中的:
import sys
def mprint(string='', dictionary=None):
if dictionary is None:
caller = sys._getframe(1)
dictionary = caller.f_locals
print string.format(**dictionary)
示例:
>>> from my_print import mprint
>>> name = 'Ismael'
>>> mprint('Hi! My name is {name}.')
Hi! My name is Ismael.
>>> new_dict = dict(country='Mars', name='Marvin',
... job='space monkey', likes='aliens')
>>> mprint("Hi! My name is {name} and I'm from {country}."
... " Isn't {name} the best name?!\nDo you know any other {name}?", new_dict)
Hi! My name is Marvin and I'm from Mars. Isn't Marvin the best name?!
Do you know any other Marvin?
请参阅: