30
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?

4 Answers4

42

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

print('{:^24s}'.format("MyString"))
Błotosmętek
  • 12,365
  • 18
  • 29
31

You can use str.center() method.

In your case, it will be: "MyString".center(24)

Boris Verkhovskiy
  • 10,733
  • 7
  • 77
  • 79
Vlad Sydorenko
  • 521
  • 3
  • 6
  • 9
    Imho better than format options because clearly expresses the intent, not only that but also one can use a fill character different from the default `" "` , as can be shown in the following example: `print("MyString".center(24, "-")` → `--------MyString--------` – gboffi Jun 27 '17 at 13:40
  • 3
    @gboffi changing the fill character is possible with `format` too: `print('{:#^24s},'.format("MyString"))` – Błotosmętek Jun 27 '17 at 13:48
  • this method allows us to use it with old formatting style `print('%24s' % "MyString".center(24))` – Saravanabalagi Ramachandran Jun 27 '17 at 13:55
7

Python 3:

You can follow the below syntax:

stringName.center(width,fillChar)

In your example:

"MyString".center(24," ")
Dipen Gajjar
  • 1,110
  • 13
  • 21
1

Ideally you would use .format().

Resource that explains center. along with others here

Kyle Becker
  • 1,242
  • 11
  • 20