我正在尝试这样做:
commands = { 'py': 'python %s', 'md': 'markdown "%s" > "%s.html"; gnome-open "%s.html"', }
命令['md'] % 'file.md'
但是就像你看到的,commmands['md'] 使用了参数 3 次,但是 commands['py'] 只使用了一次。如何在不更改最后一行的情况下重复参数(所以,只需传递一次参数?)
我正在尝试这样做:
commands = { 'py': 'python %s', 'md': 'markdown "%s" > "%s.html"; gnome-open "%s.html"', }
命令['md'] % 'file.md'
但是就像你看到的,commmands['md'] 使用了参数 3 次,但是 commands['py'] 只使用了一次。如何在不更改最后一行的情况下重复参数(所以,只需传递一次参数?)
注意:接受的答案虽然适用于旧版本和新版本的 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"'
如果您不使用 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
如果您不使用 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"; 侏儒打开“file.md.html”'