String changing on the fly
John Hunter
jdhunter at ace.bsd.uchicago.edu
Wed Oct 20 12:56:08 EDT 2004
>>>>> "Eli" == Eli Daniel <elie at flashmail.com> writes:
Eli> Hi, I'm new to Python. Can you please tell me if the
Eli> following is possible.
Eli> My users are using other scripting launguage to write
Eli> scripts. They are used to write somthing like (keeping it
Eli> simple) T = 100 do_action ('It cost $T dollars')
Eli> where the above syntax ('It cost $T dollars') is interperted
Eli> as ('It cost 100 dollars'). I saw on way of doing it by
Eli> using 'it cost '+ str(T) + ' dollars'. But trying to keep it
Eli> backward compatible, is there a way for the function
Eli> do_action, which resides in a class in a seperate file, to
Eli> take the original string (with the '$T') and replace it with
Eli> the value of T?
Python supports string interpolation with dictionaries, like
>>> d = {'first':'John', 'T':2}
>>> print '%(first)s paid %(T)s dollars'%d
John paid 2 dollars
You can use the locals dictionary to work with locally defined variables
>>> T = 5
>>> first = Bill
>>> first = 'Bill'
>>> print '%(first)s paid %(T)s dollars'%locals()
Bill paid 5 dollars
You can use regular expressions to convert $ syntax to python %(name)s
syntax
import re
def dollar_replace(matchobj):
return '%(' + matchobj.group(1) + ')s'
def like_perl(s,d):
rgx = re.compile('\$(\w+)')
fmt = re.sub('\$(\w+)', dollar_replace, s)
return fmt%d
T = 2
first = 'John'
print like_perl('$first paid cost $T dollars', locals())
You will probably want to tweak the regular expression so that any
valid python variable name is valid.
Cheers,
JDH
More information about the Python-list
mailing list