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

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.