一次传参,多次使用
我想做这个:
commands = { 'py': 'python %s', 'md': 'markdown "%s" > "%s.html"; gnome-open "%s.html"', }
commands['md'] % 'file.md'
但是你看,commands['md']这个命令用了参数三次,而commands['py']只用了一个。有没有办法在不改变最后一行的情况下重复使用这个参数?也就是说,只传一次参数?
3 个回答
1
如果你没有使用2.6版本,或者想用那些%s符号,这里还有另一种方法:
>>> 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"'
3
如果你没有使用2.6版本,你可以用字典来修改字符串:
commands = { 'py': 'python %(file)s', 'md': 'markdown "%(file)s" > "%(file)s.html"; gnome-open "%(file)s.html"', }
commands['md'] % { 'file': 'file.md' }
这里的 %()s 语法可以和普通的 % 格式化类型一起使用,并且接受其他常见的选项:http://docs.python.org/library/stdtypes.html#string-formatting-operations
11
注意:虽然被接受的答案在旧版和新版的Python中都能用,但在新版Python中不推荐使用。
因为str.format()是比较新的功能,很多Python代码还是在用%这个符号来格式化字符串。不过,由于这种旧的格式化方式最终会被从语言中移除,所以一般来说,应该使用str.format()。
所以,如果你使用的是Python 2.6或更新的版本,建议你用str.format
,而不是旧的%
符号:
>>> 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"'