2010-06-04 57 views
4

我试图做到这一点:传递参数的一个时间,但使用次数多

命令= { 'PY': '蟒蛇%S', 'MD':“降价 “%S”> “%s.html”; GNOME开 “%s.html””}

命令[ 'MD']% 'file.md'

但是就像你看到的,commmands [ 'MD']使用参数3次,但命令['py']只使用一次。如何在不更改最后一行的情况下重复该参数(所以,只需传递一次参数?)

+0

什么版本的Python? – 2010-06-04 23:23:55

回答

10

注意:接受的答案虽然适用于较旧版本和较新版本的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"' 
+0

非常感谢。这对我有效。 – 2010-06-04 23:54:18

+0

谢谢你的建议。我将使用这个解决方案。 – 2010-06-05 17:37:59

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开“file.md.html””

+0

不,在地图中使用地图而不是以格式排序,因为至少是Python 2.4。另外,你的例子不能和其他值一起使用,'commands ['py']%tuple(['some.file'] * 3)' – 2010-06-05 03:17:17

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' } 

的%()的语法适用于任何正常的%格式化程序类型并接受常用的其他选项:http://docs.python.org/library/stdtypes.html#string-formatting-operations

+0

即使在老的python中也能工作。太好了! – 2010-06-05 00:29:42

+0

我觉得在python2.6的,第二行应该是: 命令[ 'MD']%{ '文件': 'file.md'} 否则有KeyError异常 – 2010-06-05 02:14:33

+0

@xiao,是啊,是我不好。最近我一直在做太多的Javascript :) – lambacck 2010-06-05 15:36:20