Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter one time, but use more times

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

like image 985
Gabriel L. Oliveira Avatar asked Dec 07 '22 03:12

Gabriel L. Oliveira


2 Answers

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"'
like image 148
Mark Byers Avatar answered Dec 27 '22 20:12

Mark Byers


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

like image 44
lambacck Avatar answered Dec 27 '22 19:12

lambacck