默认替换python脚本中的%s

pra*_*ada 15 python string substitution

有时在Python脚本中,我看到如下行:

cmd = "%s/%s_tb -cm cond+line+fsm -ucli -do \"%s\""
Run Code Online (Sandbox Code Playgroud)

%s上面的行在哪里被替换?Python有一些字符串堆栈,它会弹出并替换它们%s吗?

Hur*_*ile 19

python字符串格式的基础知识

不是你的代码行的具体答案,但既然你说你是python的新手,我以为我会以此为例来分享一些快乐;)

内联列表的简单示例:

>>> print '%s %s %s'%('python','is','fun')
python is fun
Run Code Online (Sandbox Code Playgroud)

使用字典的简单示例:

>>> print '%(language)s has %(number)03d quote types.' % \  
...       {"language": "Python", "number": 2}
Python has 002 quote types
Run Code Online (Sandbox Code Playgroud)

如有疑问,请查看python官方文档 - http://docs.python.org/library/stdtypes.html#string-formatting


Joh*_*Jr. 19

稍后将使用以下内容:

print cmd % ('foo','boo','bar')
Run Code Online (Sandbox Code Playgroud)

您所看到的只是一个带有字段的字符串赋值,稍后将填充该字段.


zee*_*kay 17

它被用于字符串插值.该%s由字符串替换.您使用模运算符(%)进行字符串插值.字符串将在左侧,替换各种的值%s在右侧,在元组中.

>>> s = '%s and %s'

>>> s % ('cats', 'dogs' )
<<< 'cats and dogs'
Run Code Online (Sandbox Code Playgroud)

如果你只有一个角色,你可以忘记元组.

>>> s = '%s!!!'

>>> s % 'what'
<<< 'what!!!'
Run Code Online (Sandbox Code Playgroud)

在较新版本的python中,推荐的方法是使用format字符串类型的方法:

>>> '{0} {1}'.format('Hey', 'Hey')
<<< 'Hey Hey'
Run Code Online (Sandbox Code Playgroud)