Python 字符串格式

编程入门 行业动态 更新时间:2024-10-26 14:30:49
本文介绍了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 字符串格式

本文发布于:2023-08-01 08:49:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1266990.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   格式   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!