truncate and pad using format specification mini language

。_饼干妹妹 提交于 2019-12-13 11:45:11

问题


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!


回答1:


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'


来源:https://stackoverflow.com/questions/14302815/truncate-and-pad-using-format-specification-mini-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!