Default substituting %s in python scripts

情到浓时终转凉″ 提交于 2019-11-29 17:05:15

问题


Sometimes in Python scripts I see lines like:

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

Where is the %s in the above line substituted? Does Python have some stack of strings and it pops them and replaces %s?


回答1:


That would be later used in something like:

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

What you're seeing is just a string assignment with fields in it which will later be filled in.




回答2:


Basics of python string formatting

Not a specific answer to your line of code, but since you said you're new to python I thought I'd use this as an example to share some joy ;)

Simple Example Inline With a List:

>>> print '%s %s %s'%('python','is','fun')
python is fun

Simple Example Using a Dictionary:

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

When in doubt, check the python official docs - http://docs.python.org/library/stdtypes.html#string-formatting




回答3:


It's being used for string interpolation. The %s is replaced by a string. You use the modulo operator (%) to do string interpolation. The string will be on the left side, the values to substitute for the various %s are on the right, in a tuple.

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

>>> s % ('cats', 'dogs' )
<<< 'cats and dogs'

If you have just a single character you can forget the tuple.

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

>>> s % 'what'
<<< 'what!!!'

In newer versions of python the recommend way is to use the format method of the string type:

>>> '{0} {1}'.format('Hey', 'Hey')
<<< 'Hey Hey'


来源:https://stackoverflow.com/questions/5954260/default-substituting-s-in-python-scripts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!