73

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.

2 Answers 2

112

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.

11
  • 6
    Is there a builtin for showing a truncation character as well? Like an ellipsis suffix when the data is truncated like so? Aug 17, 2015 at 16:14
  • 20
    Don't forget to give a width and a precision: {:5.5}. This guarantees that the output will always be 5 characters which is probably what OP wanted.
    – Harvey
    Apr 11, 2016 at 0:05
  • 1
    @falsetru : Would you be willing to add Harvey's suggestion to your answer?
    – Neal Gokli
    Aug 10, 2018 at 19:20
  • 4
    Is it possible to truncate the beginning of the string instead of the end? Feb 28, 2019 at 9:10
  • 4
    You can make it work for non-strings by forcing them to stringify with !s: e.g. f'{123456789!s:5.5s}' => '12345'
    – Shabble
    Jan 3, 2021 at 23:19
9

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.