String Formatting with truncating and ellipses
A simple way to format a string that exceeds a certain length by truncating it and adding ellipses.
Example
long_word = Truncate("Supercalifragilisticexpialidocious")
formatted_name = f"A long word: {long_word:t10}"
print(formatted_name) # Output: "A long word: Supercalif…"
We have good methods to format and round decimals already. (PEP 3101, PEP 378)
Formatting numbers
print(f"Here's a number: {10_000/7:,.2f}") #Output: "Here's a number: 1,428.57"
Why not have a similar feature for strings? I’ve often run into scenarios where I’m dealing with dynamic data such as names of people or companies that I am printing out to a component or whatever and end up having to make a function that does this—checks if the string exceeds a certain length and, if so, truncates it and adds ellipses (…). It’d be nice if there were a simple string function of string formatting method of doing this inherently.
Demonstrative Example Code
Here’s a demonstration of a class implementing this:
class Truncate:
def __init__(self, string):
self.string = string
def __format__(self, format_spec):
max_length = int(format_spec[1:]) if format_spec.startswith('t') else None
if max_length is not None and len(self.string) > max_length:
return self.string[:max_length] + '…'
return self.string
# Example usage
long_word = Truncate("Supercalifragilisticexpialidocious")
formatted_name = f"A long word: {long_word:t10}"
print(formatted_name) # Output: "A long word: Supercalif…"
This example also accepts negative indexing in stride with python’s ability to do such.
formatted_name = f"A long word: {long_word:t-20}"
print(formatted_name) # Output: "A long word: Supercalifragi…"
The details of exactly how this would work are yet to be determined. But this would be a useful feature and would improve Python’s string formatting usefulness.
Extras
While we’re discussing it, there might also be a use case for truncating from the left side and adding ellipses there instead of the right; e.g.,
formatted_name = f"A long word: {long_word:l5}"
print(formatted_name) # Output: "A long word: …califragilisticexpialidocious"