Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

truncate and pad using format specification mini language

I'm currently writing code which pads a string with spaces, using Python's format specification mini language:

print('''{user:<10}, you're welcome!'''.format(user='John Doe'))

The output is:

John Doe  , you're welcome!

However, if user's name is something like 'Joooooooooooohn Doe', I'd like to output:

Jooooooooo, you're welcome!

Is there a way to perform truncation AND padding using the format specification mini language?

Thanks!

like image 631
Giuc Avatar asked Jan 13 '13 11:01

Giuc


1 Answers

From the page you linked to:

For non-number types [precision] indicates the maximum field size - in other words, how many characters will be used from the field content. The precision is not allowed for integer values.

Precision is introduced by a period

format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]

So the correct format string is {user:<10.10}.

>>> '{0:<10.10}'.format('1234567')
'1234567   '

>>> '{0:<10.10}'.format('123456789034')
'1234567890'
like image 165
Paul Hankin Avatar answered Oct 21 '22 06:10

Paul Hankin