Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python .format slice long string and add dots

Tags:

python

string

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

like image 699
Zhuo.M Avatar asked Mar 15 '13 10:03

Zhuo.M


1 Answers

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...'
like image 55
Martijn Pieters Avatar answered Sep 19 '22 06:09

Martijn Pieters