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!
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With