In Python, How can I make long string "Foo Bar" became "Foo..." by using advance formatting and don't change short string like "Foo"?
"{0:.<-10s}".format("Foo Bar")
just makes string fill with dots
You'll need to use a separate function for that; the Python format mini language does not support truncating:
def truncate(string, width):
if len(string) > width:
string = string[:width-3] + '...'
return string
"{0:<10s}".format(truncate("Foo Bar Baz", 10))
which outputs:
>>> "{0:<10s}".format(truncate("Foo", 10))
'Foo '
>>> "{0:<10s}".format(truncate("Foo Bar Baz", 10))
'Foo Bar...'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With