How to pad with n characters in Python

Question:

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“.

Asked By: Gusto

||

Answers:

With Python2.6 or better, there’s no need to define your own function; the string format method can do all this for you:

In [18]: '{s:{c}^{n}}'.format(s='dog',n=5,c='x')
Out[18]: 'xdogx'

Using f-string: f'{"dog":x^5}'

Answered By: unutbu

It looks like you’re only looking for pointers, not a complete solution. So here’s one:

You can multiply strings in python:

>>> "A" * 4
'AAAA'

Additionally I would use better names, instead of s I’d use text, which is much clearer. Even if your current professor (I suppose you’re learning Python in university.) uses such horrible abbreviations.

Answered By: Georg Schölly

well, since this is a homework question, you probably won’t understand what’s going on if you use the “batteries” that are included.

def pad_with_n_chars(s, n, c):
    r=n - len(s)
    if r%2==0:
       pad=r/2*c
       return pad + s + pad
    else:
       print "what to do if odd ? "
       #return 1
print pad_with_n_chars("doggy",9,"y")

Alternatively, when you are not schooling anymore.

>>> "dog".center(5,"x")
'xdogx'
Answered By: ghostdog74
print '=' * 60
header = lambda x: '%s%s%s' % ('=' * (abs(int(len(x)) - 60) / 2 ),x,'=' * (abs(int(len(x)) - 60) / 2 ) )
print header("Bayors")
Answered By: Kevin Postal

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
Answered By: Aditya Advani

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
Answered By: GooDeeJAY
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.