Ford
Ford

Reputation: 2597

Python string format, drop characters if too long

Currently I have a template for printing out columns in a table to stdout:

template = "%-5s%-8s%-20s%-20s%-20s%-15s%-15s%-15s%-15s%-15s"

I use it as so to print out my rows

print template % row

However, some columns in the row go over the amount of characters (e.g., the first string should be limited to the space it's allocated (5) by the template). Is there a function or specifier I can use with the string format that will chop characters off the end of the string so that it fits the allocated space (or better yet, a length that I specify as the limit). That is without doing something like:

for i in range(0, len(row)):
    row[col] = row[col][0:limit[i]]

Upvotes: 0

Views: 360

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799580

Specify precision on the string format.

>>> '%.5s' % ('1234567890',)
'12345'

Upvotes: 1

Related Questions