新格式让我们可以这样做:'{:.<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 字符串格式
发布评论