5

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

Zhuo.M
  • 466
  • 3
  • 18
  • Does this answer your question? [Python truncate a long string](https://stackoverflow.com/questions/2872512/python-truncate-a-long-string) – Jeyekomon Jan 19 '21 at 13:09

2 Answers2

7

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...'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
-2

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..........
Chetan
  • 1,217
  • 2
  • 13
  • 27
  • Your solution will print dots even when the text isn't truncated or the lenght isn't gerater than the minimum. – Hamlett Feb 27 '18 at 04:15