且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 字符串格式 - 旧的 `%` 与新的 `str.format`

更新时间:2023-09-14 13:17:58

对于使用 new-format 做可变长度,可以使用替换嵌套 -

>>>'{:{}<{}}'.format('##','.',12)'##…………'>>>'{:{}<{}}'.format('##','-',12)'##-----------'>>>'{:{}<{}}'.format('##','-',20)'##------------------'

偶数空格作为填充字符 -

>>>'{:{}<{}}'.format('##',' ',20)'##'

请注意,您并不总是需要使用替换的嵌套,您也可以直接在格式中指定它们-

>>>'{:

您还可以指定每个参数的位置来决定哪个参数去哪里.示例 -

>>>'{2:{0}

New formatting lets us do this: '{:.<12}'.format('##') - optional fill character.
Can we do that using old formatting?
(I know we can fill with spaces '%-12s' % '##' )

Also, old formatting lets us do this: '%-*s' % (12, '##') - variable length.
Can we do that using new formatting?

For doing variable length using new-format , you can use nesting of replacements -

>>> '{:{}<{}}'.format('##','.',12)
'##..........'
>>> '{:{}<{}}'.format('##','-',12)
'##----------'
>>> '{:{}<{}}'.format('##','-',20)
'##------------------'

Even spaces as fill character -

>>> '{:{}<{}}'.format('##',' ',20)
'##                  '

Please note you do not always need to use nesting of replacements, you can directly specify them in the format as well -

>>> '{: <12}'.format('##')
'##          '

You can also specify the position of each argument to decide which argument goes where. Example -

>>> '{2:{0}<{1}}'.format('.',12,'##')
'##..........'
>>> '{0:{1}<{2}}'.format('##','-',20)
'##------------------'