In this tutorial, we will learn how to center-align text in Python using different methods. Center-aligning text is a useful technique for formatting text in various situations such as creating reports, and tables, or simply making text look more aesthetically pleasing.
Method 1: Using the str.format() function
Python’s str.format()
function allows you to perform simple positional formatting, which can be useful to center-align text. Here’s an example:
1 2 3 4 5 |
text = "Center Align" width = 20 center_aligned_text = "{:^20}".format(text) print(center_aligned_text) |
In this example, we used the ^
character inside the format specifier to indicate center alignment. The number 20
specifies the width, in characters, of our output string. The resulting output will be:
Center Align
Method 2: Using the str.center() method
Another way to center-align text in Python is by using the str.center()
method. This method is called on a string object and takes a width as its first argument. You can also optionally pass a second argument to fill the empty spaces with a specific character. Here’s an example:
1 2 3 4 5 6 7 8 |
text = "Center Align" width = 20 center_aligned_text = text.center(width) print(center_aligned_text) center_aligned_text_with_filler = text.center(width, '*') print(center_aligned_text_with_filler) |
The output of this code will be:
Center Align ****Center Align****
In the second example, we used the *
character as a filler.
Conclusion
In this tutorial, we’ve explored two different methods to center-align text in Python: using the str.format()
function and the str.center()
method. Both methods are quite handy for formatting and aligning text, so choose the one that best fits your needs!