Python脚本中默认替换%s
有时候在Python脚本中,我会看到这样的代码:
cmd = "%s/%s_tb -cm cond+line+fsm -ucli -do \"%s\""
那么,上面那行中的%s
是在哪里被替换的呢?Python是不是有一个字符串的堆栈,然后把它们弹出来替换%s
?
3 个回答
20
这个方法是用来进行字符串插值的。%s
会被一个字符串替换掉。你可以用取模运算符(%
)来实现字符串插值。字符串放在左边,而要替换的值则放在右边,以元组的形式出现。
>>> s = '%s and %s'
>>> s % ('cats', 'dogs' )
<<< 'cats and dogs'
如果你只有一个字符,就可以不使用元组了。
>>> s = '%s!!!'
>>> s % 'what'
<<< 'what!!!'
在更新版本的Python中,推荐使用字符串类型的format
方法:
>>> '{0} {1}'.format('Hey', 'Hey')
<<< 'Hey Hey'
21
这段代码稍后会在类似的地方使用:
print cmd % ('foo','boo','bar')
你看到的其实就是一个字符串的赋值,里面有一些字段,之后会把这些字段填上具体的内容。
22
Python字符串格式化基础
这不是针对你代码的具体回答,但因为你说你是Python新手,我想用这个例子来分享一些乐趣;)
简单的列表内联示例:
>>> print '%s %s %s'%('python','is','fun')
python is fun
使用字典的简单示例:
>>> print '%(language)s has %(number)03d quote types.' % \
... {"language": "Python", "number": 2}
Python has 002 quote types
如果有疑问,可以查看Python的官方文档 - http://docs.python.org/library/stdtypes.html#string-formatting