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?)
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"'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With