Categories
Python Answers

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

Spread the love

Sometimes, we want to print a string at a fixed width with Python.

In this article, we’ll look at how to print a string at a fixed width with Python.

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

To print a string at a fixed width with Python, we can use the string’s format method with a format code.

For instance, we write:

s = '{0: <5}'.format('s')
print(s)

to return a string with length 5.

The 's' string is padded to length 5 with empty trailing spaces.

Therefore, print prints ''s '.

Conclusion

To print a string at a fixed width with Python, we can use the string’s format method with a format code.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *