Python string formatting - old `%` vs new `str.format` -


new formatting lets this: '{:.<12}'.format('##') - optional fill character.
can using old formatting?
(i know can fill spaces '%-12s' % '##' )

also, old formatting lets this: '%-*s' % (12, '##') - variable length.
can using new formatting?

for doing variable length using new-format , can use nesting of replacements -

>>> '{:{}<{}}'.format('##','.',12) '##..........' >>> '{:{}<{}}'.format('##','-',12) '##----------' >>> '{:{}<{}}'.format('##','-',20) '##------------------' 

even spaces fill character -

>>> '{:{}<{}}'.format('##',' ',20) '##                  ' 

please note not need use nesting of replacements, can directly specify them in format -

>>> '{: <12}'.format('##') '##          ' 

you can specify position of each argument decide argument goes where. example -

>>> '{2:{0}<{1}}'.format('.',12,'##') '##..........' >>> '{0:{1}<{2}}'.format('##','-',20) '##------------------' 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -