Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: String Formatter Align center [duplicate]

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?

like image 760
Saravanabalagi Ramachandran Avatar asked Jun 27 '17 13:06

Saravanabalagi Ramachandran


People also ask

How do I center a string format in Python?

Python String center() MethodThe center() method will center align the string, using a specified character (space is default) as the fill character.

How do you align text in Python?

You can use the :> , :< or :^ option in the f-format to left align, right align or center align the text that you want to format. We can use the fortmat() string function in python to output the desired text in the order we want.

How do you right align a format string?

There are several different ways to right-justify strings using the Format function: Use the @ character. Use the RSet function. Use workarounds with the Format$ function.

How do you justify a string in Python?

Python String rjust() MethodPython string method rjust() returns the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).


1 Answers

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

print('{:^24s}'.format("MyString")) 
like image 200
Błotosmętek Avatar answered Sep 17 '22 15:09

Błotosmętek