How to print a String at a fixed width with Python?

Estimated read time 1 min read

To print a string at a fixed width in Python, you can use the str.ljust(), str.rjust(), or str.center() methods. These methods allow you to specify the width of the output string and the padding character.

Here’s an example of each method:

  1. Using ljust():
text = "Hello"
width = 10
padding_char = "-"

output = text.ljust(width, padding_char)
print(output)
  1. Using rjust():
text = "Hello"
width = 10
padding_char = "-"

output = text.rjust(width, padding_char)
print(output)
  1. Using center():
text = "Hello"
width = 10
padding_char = "-"

output = text.center(width, padding_char)
print(output)

In each method, the width parameter specifies the total width of the output string, and the padding_char parameter determines the character used for padding. The ljust() method left-justifies the text, rjust() right-justifies it, and center() centers it within the specified width.

Feel free to adjust the text, width, and padding_char values according to your specific requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply