开发者

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 com开发者_Go百科mmands['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'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"'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜