How to truncate a string using str.format in 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)