[Python-ideas] Format character to center strings

Steven D'Aprano steve at pearwood.info
Sat Mar 28 18:37:51 CET 2015


On Sat, Mar 28, 2015 at 10:11:49AM -0700, David Blaschke wrote:
> Centered=same amount of white space on the left and to the right of
> the text.  This depends on the font being used, especially whether it
> is a fixed or proportional font.

You're over-thinking it. Python already offers two ways of centering 
strings, with the distance measured in number-of-characters rather than 
pixels or points.

py> "Hello world!".center(20)
'    Hello world!    '
py> "{:^20}".format("Goodbye everyone!")
' Goodbye everyone!  '

Left and right justification also pad the string to a fixed width in 
characters, not in pixels.


-- 
Steve


More information about the Python-ideas mailing list