How to Print a String at a Fixed Width in Python?

Estimated read time 2 min read

To print a string at a fixed width in Python, you can use the string formatting method. This method allows you to specify the width of the field where the string will be printed. If the string is shorter than the field width, it will be padded with spaces to fill the remaining space. If the string is longer than the field width, it will be truncated to fit within the field.

Here is an example:

my_string = "hello world"

print("{:<20}".format(my_string))

In this example, we have a string called my_string with the value “hello world”. We use the string formatting method with the "<" character to left-align the string within a field of width 20. The field width is specified with the 20 parameter in the curly braces.

The output of this code will be:

hello world         

Note that the field width includes the length of the string plus any padding spaces that are added. If you want to right-align the string, you can use the ">" character instead of the "<" character. If you want to center-align the string, you can use the "^" character. For example:

my_string = "hello world"

print("{:>20}".format(my_string))   # right-aligned
print("{:^20}".format(my_string))   # center-aligned

The output of this code will be:

         hello world
    hello world     

Note that you can also use the f-string format to achieve the same result. Here is an example:

my_string = "hello world"
width = 20
print(f"{my_string:<{width}}")  # left-aligned
print(f"{my_string:^{width}}")  # center-aligned
print(f"{my_string:>{width}}")  # right-aligned

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply