简体   繁体   中英

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!

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM