python %s深入解析

时间:2022-08-03 06:10:21

默认我们通常用字符串填充它

'Keep %s, and you will aways make %' % ('moving', 'it')

如果你就此止步,那就错过了一些神乎其技的用法

比如:

arr=[1,2,3,4]
'arr=%s'%arr

将输出 'arr=[1,2,3,4]'

dct = {'name':'tommy', 'major':'software engineer'}
'info of tommy:%s'%dct

将输出:"info of tommy:{'major': 'software engineer', 'name': 'tommy'}"

简单来说, '%s'的本质是调用对象的 str()方法。以下为证:

>>> class Data():
def __str__(self):
return 'I am Data' >>> '%s'%Data()
'I am Data'

回过头来看, 为啥下面会报错呢

>>> '%s'%(1,2,3)

Traceback (most recent call last):
File "<pyshell#99>", line 1, in <module>
'%s'%(1,2,3)
TypeError: not all arguments converted during string formatting

因为,对tuple做了特别的解析处理!具体是:

碰到tuple, 依次调用里面元素的str方法!如果元素也是tuple,同样也调用str方法,不再做特别处理!

>>> 'tuple(dict ==> %s, list==>%s, tuple==>%s, string=>%s'%({'A':1}, ['B','C'], ('T1','T2'), 'str')
"tuple(dict ==> {'A': 1}, list==>['B', 'C'], tuple==>('T1', 'T2'), string=>str"

转载请注明来源:http://www.cnblogs.com/Tommy-Yu/p/5768089.html

谢谢!