Python: String Formatter Align center

Saravanabalagi Ramachandran picture Saravanabalagi Ramachandran · Jun 27, 2017 · Viewed 35.4k times · Source
print('%24s' % "MyString")     # prints right aligned
print('%-24s' % "MyString")    # prints left aligned

How do I print it in the center? Is there a quick way to do this?

I don't want the text to be in the center of my screen. I want it to be in the center of that 24 spaces. If I have to do it manually, what is the math behind adding the same no. of spaces before and after the text?

Answer

Błotosmętek picture Błotosmętek · Jun 27, 2017

Use the new-style format method instead of the old-style % operator, which doesn't have the centering functionality:

print('{:^24s}'.format("MyString"))