Alternative dictionary output format?
rael at my-deja.com
rael at my-deja.com
Fri Jun 4 10:55:42 EDT 1999
I would like to be able to take a string which contains C-format
extension variables (e.g., "%(foo)s") and format it with a dictionary in
the standard way, except I would like the format to only substitute for
the recognized variables and to ignore other instances of percent signs.
For example, given this program:
s = "%(href)s/foo/bar?x=%m&y=%n"
d = {'href': "http://www.gomer.com"}
u = s % d
print s
running it produces:
% python t.py
Traceback (innermost last):
File "t.py", line 3, in ?
u = s % d
TypeError: not enough arguments for format string
And this program:
s = "%m foobar %(href)s/foo/bar?x=%m&y=%n"
d = {'href': "http://www.gomer.com"}
u = s % d
print s
produces:
% python t.py
Traceback (innermost last):
File "t.py", line 3, in ?
u = s % d
ValueError: unsupported format character 'm' (0x6d)
What I would like to write:
s = "%m foobar %(href)s/foo/bar?x=%m&y=%n"
d = {'href': "http://www.gomer.com"}
u = format_ignoring_non_variable_percent_signs(s, d)
print s
And what I would like the behavior to be:
% python t.py
%m foobar http://www.gomer.com/foo/bar?x=%m&y=%n
Is there any way to surface the C interface for the '%' format operator
and to allow an option to effectively wrap each format attempt with a
try/except/pass block?
I realize there are other ways to do this (regular expression
substitution, write my own C extension, etc.), but formatting a string
with multiple variables using a dictionary and the format operator is
extremely convenient (and I imagine relatively effiecient), and I
thought others may have come across this as well.
Bill
--
r a e l @
d e j a .
c o m
Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
More information about the Python-list
mailing list