Add Padding To A String In Python

January - 2022

Use .ljust() and .rjust() to add padding to string.

example = 'a'
padded = example.ljust(5)

print(f'---{padded}---')

Outputs:

---a    ---

example = 'a'
padded = example.rjust(5)

print(f'---{padded}---')

Outputs:

---    a---

You can also set the character to pad with:

example = 'a'
padded = example.ljust(5, 'x')

print(f'---{padded}---')

Outputs:

---axxxx---