Python 字符串格式 - 旧的 `%` 与新的 `str.format` [英] Python string formatting - old `%` vs new `str.format`

查看:50
本文介绍了Python 字符串格式 - 旧的 `%` 与新的 `str.format`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新格式让我们可以这样做:'{:.<12}'.format('##') - 可选的填充字符.
我们可以使用旧格式来做到这一点吗?
(我知道我们可以用空格填充 '%-12s' % '##' )

此外,旧格式允许我们这样做:'%-*s' % (12, '##') - 可变长度.
我们可以使用新格式来做到这一点吗?

解决方案

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

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

偶数空格作为填充字符 -

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

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

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

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

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

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)
'##------------------'

这篇关于Python 字符串格式 - 旧的 `%` 与新的 `str.format`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆