How to pad a string to a fixed length with spaces in Python? How to pad a string to a fixed length with spaces in Python? python python

How to pad a string to a fixed length with spaces in Python?


This is super simple with format:

>>> a = "John">>> "{:<15}".format(a)'John           '


You can use the ljust method on strings.

>>> name = 'John'>>> name.ljust(15)'John           '

Note that if the name is longer than 15 characters, ljust won't truncate it. If you want to end up with exactly 15 characters, you can slice the resulting string:

>>> name.ljust(15)[:15]


If you have python version 3.6 or higher you can use f strings

>>> string = "John">>> f"{string:<15}"'John           '

Or if you'd like it to the left

>>> f"{string:>15}"'          John'

Centered

>>> f"{string:^15}"'     John      '

For more variations, feel free to check out the docs: https://docs.python.org/3/library/string.html#format-string-syntax