在python脚本中默认替换%s

2024-06-08 14:46:01 发布

您现在位置:Python中文网/ 问答频道 /正文

有时在Python脚本中,我看到这样的行:

cmd = "%s/%s_tb -cm cond+line+fsm -ucli -do \"%s\""

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


Tags: 字符串脚本cmd堆栈linecmdotb
3条回答

它被用于字符串插值。%s被字符串替换。使用模运算符(%)进行字符串插值。字符串将位于左侧,用于替换各种%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'

以后会用在类似于:

print cmd % ('foo','boo','bar')

您所看到的只是一个字符串赋值,其中包含稍后将填充的字段。

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

相关问题 更多 >