Ways To Align Text Strings In Python

In this article, I’ll show you various ways to align strings in Python. There are many different ways we can align strings in Python. Let’s have a look at those:

Left Align

For left-aligned text, you can use ljust(…) function, which stands for left justification.

my_text = “Shift me.”
print(my_text.ljust(25) )

The above lines will display left-aligned text with a length of 25.

The alternate way of doing this is by using format(…) function as shown below:

my_text = “Shift me.”
print(format(my_text,’>25'))

Right Align

For right-aligned text, you can use rjust(…) function, which stands for right justification.

my_text = “Shift me.”
print(my_text.rjust(25)

The above lines will display right-aligned text with a length of 25.

The alternate way of doing this is by using format(…) function as shown below:

my_text = “Shift me.”
print(format(my_text,’<25'))

Center Align

For center-aligned text, you can use center(…) function.

my_text = “Place me to the center.”
print(my_text.center(25)

The alternate way of doing this is by using format(…) function as shown below:

my_text = “Place me to the center.”
print(format(my_text,’^25'))

Fill Extra Space With Other Character

If you want to fill empty space with the character of your choice, you can also do that. Just type in below lines of code:

my_text = “Shift me.”
print(format(my_text,’*>25s'))

or

print(my_text.ljust(25,’*’) )

Takeaway

The best part with format(…) function is, it works with other types of values too and is not constrained to only strings. If you want to read more about format(…) function, check this link.

Hope you enjoyed aligning your strings in Python. Do not forget to watch the hands-on recording of this article on my YouTube channel named Shweta Lodha.


Similar Articles