Text Alignment in Python
Table of contents
There are methods in python on str class which are used to adjust the padding on texts. Ex:
hello = 'Hello'
print(hello.ljust(21, '-'))
print(hello.center(21, '-'))
print(hello.rjust(21, '-'))
#Expected output for this would be
Hello---------------- # (for ljust method)
--------Hello-------- # (for center method)
----------------Hello # (for rjust method)
Methods for padding
ljust
, rjust
, center
these methods are used on string data type for adjusting left, right and center padding respectively for a string or text
Syntax for methods are
width is total size of container and character is the char that should be filled in empty space if text size is less than width. Default value of character is space
Example for simple usages
Building a menu for a game
Generally, when we see any game menu, we see a similar kind of texts like the one given below
New Game
Continue
Options
This could be performed in python using these methods.
menu = ["New Game", "Load Game", "Options"] width = 30 for item in menu: centered_item = item.center(width) print(centered_item)
Let's take a hypothetical situations where you need to align some text as per the given problem statements, (say in any interview or there is a hackerrank question on it.)
door_mat = '' # final door mat design to return welcome = 'WELCOME' # 'Welcome' string to be used design = '.|.' # we can use this particular design (n,m) = input().split(' ') mid = int(n)//2 # finding mid point of all rows for i in range(int(n)): if i < mid: # design*odd number in increasing format till mid value door_mat += (design*(2*i+1)).center(int(m), '-') + '\n' elif i == mid: # center the welcome string door_mat += welcome.center(int(m), '-') + '\n' else: # help_design_value is for generating odd number of design in reverse order help_design_value = int(n) - i - 1 door_mat += (design*(2*help_design_value+1)).center(int(m), '-') + '\n' print(door_mat)
There are so many other uses like making report, generating table headers etc.
Subscribe to my newsletter
Read articles from Rakesh Verma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by