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
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...'
You can configure how many number of dots you need and after how many number of characters. I am assigning 10 dots after 3 characters
text = "Foo Bar"
dots = "." * 10
output = text[0:3] + dots
print output
The output is:
Foo..........