Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 966
famousgarkin Avatar asked Jun 06 '14 07:06

famousgarkin


People also ask

How do I truncate a string in Python?

The other way to truncate a string is to use a rsplit() python function. rsplit() function takes the string, a delimiter value to split the string into parts, and it returns a list of words contained in the string split by the provided delimiter.

How do I remove a substring from a string in Python?

Use the String translate() method to remove all occurrences of a substring from a string in python.

How do you remove a character from a string in Python?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.


1 Answers

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.

like image 62
falsetru Avatar answered Sep 24 '22 22:09

falsetru