How to pad with n characters in Python

Viewed 48359

I should define a function pad_with_n_chars(s, n, c) that takes a string 's', an integer 'n', and a character 'c' and returns a string consisting of 's' padded with 'c' to create a string with a centered 's' of length 'n'. For example, pad_with_n_chars(”dog”, 5, ”x”) should return the string "xdogx".

6 Answers

yeah just use ljust or rjust to left-justify (pad right) and right-justify (pad left) with any given character.

For example ... to make '111' a 5 digit string padded with 'x'es

In Python3.6:

>>> '111'.ljust(5, 'x')
111xx

>>> '111'.rjust(5, 'x')
xx111

In Python 3.x there are string methods: ljust, rjust and center.

I created a function:

def header(txt: str, width=45, filler='-', align='c'):
    assert align in 'lcr'
    return {'l': txt.ljust, 'c': txt.center, 'r': txt.rjust}[align](width, filler)

print(header("Hello World"))
print(header("Hello World", align='l'))
print(header("Hello World", align='r'))

Output:

-----------------Hello World-----------------
Hello World----------------------------------
----------------------------------Hello World
Related