2010-06-04 72 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