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".
36
votes
6 Answers
57
votes
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'
32
votes
21
votes
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.
1
votes
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'
1
votes
0
votes
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
pad_with_n_charsfunction. - PaulMcG