如何在 Python 中使用 str.format 截断字符串? [英] How to truncate a string using str.format in Python?

查看:47
本文介绍了如何在 Python 中使用 str.format 截断字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 str.format 在 Python 中?甚至有可能吗?

width 参数="noreferrer">格式规范迷你语言:

format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]...宽度 ::= 整数...

但指定它显然只适用于填充,而不是截断:

<预><代码>>>>'{:5}'.format('aaa')'啊'>>>'{:5}'.format('aaabbbccc')'aaabbbccc'

所以它实际上是最小宽度而不是宽度.

我知道我可以对字符串进行切片,但我在这里处理的数据是完全动态的,包括格式字符串和输入的参数.我不能直接去明确地切片.

解决方案

使用 .precision 代替:

<预><代码>>>>'{:5.5}'.format('aaabbbccc')'aaabb'

根据格式规范Mini-语言:

<块引用>

precision 是一个十进制数,表示对于用 'f''F 格式化的浮点值,小数点后应显示多少位数字' ,或用 'g''G' 格式化的浮点值的小数点前后.对于非数字类型,该字段表示最大字段大小 - 换句话说,字段内容中将使用多少个字符.精度不允许用于整数值.

How to truncate a string using str.format in Python? Is it even possible?

There is a width parameter mentioned in the Format Specification Mini-Language:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
...
width       ::=  integer
...

But specifying it apparently only works for padding, not truncating:

>>> '{:5}'.format('aaa')
'aaa  '
>>> '{:5}'.format('aaabbbccc')
'aaabbbccc'

So it's more a minimal width than width really.

I know I can slice strings, but the data I process here is completely dynamic, including the format string and the args that go in. I cannot just go and explicitly slice one.

解决方案

Use .precision instead:

>>> '{:5.5}'.format('aaabbbccc')
'aaabb'

According to the documentation of the Format Specification Mini-Language:

The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with 'f' and 'F', or before and after the decimal point for a floating point value formatted with 'g' or 'G'. For non-number types the field indicates the maximum field size - in other words, how many characters will be used from the field content. The precision is not allowed for integer values.

这篇关于如何在 Python 中使用 str.format 截断字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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