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

0

4 Answers 4

70

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

print('{:^24s}'.format("MyString"))
Sign up to request clarification or add additional context in comments.

5 Comments

Oh wow, this should be helpful for all python newbies like me; I wouldn't have noticed it if I started all the way without asking this question
This method reduces the space the longer the string, until the point where there is no space.
print(f'{"MyString":^24s}')
What does the s at the end do?
s stands for string - there are also other format specifications like d for decimals, f for fixed-point floats etc., see docs.python.org/3/library/string.html
46

You can use str.center() method.

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

3 Comments

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 changing the fill character is possible with format too: print('{:#^24s},'.format("MyString"))
this method allows us to use it with old formatting style print('%24s' % "MyString".center(24))
11

Python 3:

You can follow the below syntax:

stringName.center(width,fillChar)

In your example:

"MyString".center(24," ")

Comments

2

Ideally you would use .format().

Resource that explains center. along with others here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.