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

PythonStringString Formatting

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

you may truncate by the precision parameter alone:

>>> '{:.1}'.format('aaabbbccc')
'a'

the size parameter is setting the padded size:

>>> '{:3}'.format('ab')
' ab'

alex

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfamousgarkinView Question on Stackoverflow
Solution 1 - PythonfalsetruView Answer on Stackoverflow
Solution 2 - PythonalexView Answer on Stackoverflow