views:

130

answers:

3

I'm trying to do this:

commands = { 'py': 'python %s', 'md': 'markdown "%s" > "%s.html"; gnome-open "%s.html"', }

commands['md'] % 'file.md'

But like you see, the commmands['md'] uses the parameter 3 times, but the commands['py'] just use once. How can I repeat the parameter without changing the last line (so, just passing the parameter one time?)

+6  A: 

Note: The accepted answer, while it does work for both older and newer versions of Python, is discouraged in newer versions of Python.

Since str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually be removed from the language, str.format() should generally be used.

For this reason if you're using Python 2.6 or newer you should use str.format instead of the old % operator:

>>> commands = {
...     'py': 'python {0}',
...     'md': 'markdown "{0}" > "{0}.html"; gnome-open "{0}.html"',
... }
>>> commands['md'].format('file.md')
'markdown "file.md" > "file.md.html"; gnome-open "file.md.html"'
Mark Byers
Thank you so much. This worked for me.
Gabriel L. Oliveira
Thank you for advice. I'll use this solution.
Gabriel L. Oliveira
+1  A: 

If you're not using 2.6 or want to use those %s symbols here's another way:

>>> commands = {'py': 'python %s',
...             'md': 'markdown "%s" > "%s.html"; gnome-open "%s.html"'
... }
>>> commands['md'] % tuple(['file.md'] * 3)

'markdown "file.md" > "file.md.html"; gnome-open "file.md.html"'

Khorkrak
nah, use of maps instead of sequnce in % formatting was there since at least python 2.4. Besides, your example won't work with the other value, `commands['py'] % tuple(['some.file'] * 3)`
Nas Banov
+2  A: 

If you are not using 2.6 you can mod the string with a dictionary instead:

commands = { 'py': 'python %(file)s', 'md': 'markdown "%(file)s" > "%(file)s.html"; gnome-open "%(file)s.html"', }

commands['md'] % { 'file': 'file.md' }

The %()s syntax works with any of the normal % formatter types and accepts the usual other options: http://docs.python.org/library/stdtypes.html#string-formatting-operations

lambacck
Works even with old pythons. Nice!
Gabriel L. Oliveira
I think in python2.6, the second line should be:commands['md'] % {'file':'file.md'}otherwise there is a keyerror
xiao
@xiao, yup, my bad. I've been doing too much Javascript lately :)
lambacck