1
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)

* besides python taste/style/standards

Is there a nicer succinct way to call it then a single letter method?
Is there anything the regex could miss?
should I use repr instead of str ?
I know that eval can be dangerous but I can't see why

I("#{some_func()}\n")

is worse then

"%s\n" % str(some_func())
3
  • 2
    It's worse because you don't have any error detection from language or IDE. Also if you forgot # user will see actual code. Moreover if you accidentally call 'I' on string that contains input from user, you will have big security hole. There are probably more reasons. Commented Aug 17, 2011 at 5:41
  • Maybe an ide or a checker but I think python just craps out with an exception either way,no? Commented Aug 17, 2011 at 5:56
  • 1
    If you have syntax error like "foo)(" Python will raise exception on module-loading time. Commented Aug 17, 2011 at 13:32

2 Answers 2

2

Not sure exactly what you're trying to accomplish, but does this work?

I = '{}\n'.format
I(some_func())

or

def I(func):
    return "%x\n" % func()
I(some_func())

Using your example from the comment,

I([x*2 for x in [1,2,3]])

works fine (though I don't know what it is you want the output to look like), as does

I(''.join((self.name, ' has ', self.number_of_children)))

but you should really just be doing

'{} has {}'.format(self.name, self.number_of_children)

which is still one line.

Sign up to request clarification or add additional context in comments.

8 Comments

I'm trying to do ruby style string interpolation
You can even do crazy stuff like I("#{[x*2 for x in [1,2,3]]}") without multiple lines. But mostly used for stuff like I(" (#{self.name}) has #{self.number_of_children}")
A simple syntax for putting variables/expressions in strings
Edited to show that stuff. I don't see how Python's syntax is any more complicated.
You can use named replacements if you want more clarity... '{name} has {num_children}'.format(name=self.name, num_children=self.num_children) which looks even more clear than the ruby version to me. Also, what's wrong with self.name + ' has ', str(self.num_children) if you want to keep it simple? Edit: You just commented you prefer this :)
|
1

This is what I came up with.

in 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)

example:

>>> 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?

See:

Python string interpolation implementation

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.