Easy "here documents" ??

Scott David Daniels Scott.Daniels at Acm.Org
Mon Dec 20 20:33:06 CET 2004

Jim Hill wrote:
> Fredrik Lundh wrote:
>>Scott David Daniels wrote:
>>>And if you enjoy building insecure stuff, try:
>>>    def fix(text, globals_=None, locals=None, quote='"'):
>>>        d = (globals_ or locals or globals()).copy()
>>>        source = text.split(quote)
>>>        source[1::2] = (str(eval(expr, d, locals or d))
[fixing the !#@!$ tab that snuck in there]
>>>        for expr in source[1::2])
>>>            return ''.join(source)
>>And if you prefer not to type so much:
>>def I(*args): return "".join(map(str, args))
>>def F(v, fmt): return ("%" + fmt) % v
> Not that I don't appreciate the suggestions from masters of the Python
> universe, but the reason I'm switching to Python from Perl is for the
> readability.  What you fells are suggesting might as well be riddled
> with dollar signs and semicolons...  <emoticon>.
Really what I was trying to showing you was that you could use eval and
do arbitrary expressions using sneaky slicing.

v[1::2] is every odd position, and it can be used for replacement.

v[1::2] = [str(eval(txt)) for txt in v[1::2]]

Is likely what you want; it got ugly when I lifted it into a function.
The cute trick is to use a quote delimiter and observe that the odd
positions are the quoted text.

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list