如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:55:33  来源:igfitidea点击:

How to truncate a string using str.format in Python?

pythonstringstring-formatting

提问by famousgarkin

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

如何str.format在 Python 中使用截断字符串?甚至有可能吗?

There is a widthparameter 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 .precisioninstead:

使用.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'对于非数字类型,该字段指示最大字段大小 - 换句话说,字段内容中将使用多少个字符。整数值不允许使用精度