如何在 Python 中使用 str.format 截断字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24076297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to truncate a string using str.format in Python?
提问by famousgarkin
How to truncate a string using str.format
in Python? Is it even possible?
如何str.format
在 Python 中使用截断字符串?甚至有可能吗?
There is a width
parameter mentioned in the Format Specification Mini-Language:
Format Specification Mini-Language 中width
提到了一个参数:
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.
我知道我可以对字符串进行切片,但是我在这里处理的数据是完全动态的,包括格式字符串和输入的参数。我不能直接去明确地对一个进行切片。
采纳答案by falsetru
Use .precision
instead:
使用.precision
来代替:
>>> '{:5.5}'.format('aaabbbccc')
'aaabb'
According to the documentation of the Format Specification Mini-Language:
根据Format Specification Mini-Language的文档:
The precisionis 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 precisionis not allowed for integer values.
的精度是指示多少位数应的小数点格式化与浮点值之后显示的十进制数
'f'
和'F'
,或之前和小数点用于与格式化的浮点值之后'g'
或'G'
。对于非数字类型,该字段指示最大字段大小 - 换句话说,字段内容中将使用多少个字符。整数值不允许使用精度。