views:

110

answers:

4

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

+10  A: 

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'
unutbu
Nice and concise!
Steve
That's pure magic!
Georg
+1. Please note that format is quite recent and probably won't work with legacy Python versions.
e-satis
A: 

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.

Georg
A: 

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'
ghostdog74
+1  A: 
>>> dir(string)

['Formatter',
 'Template',
 '_TemplateMetaclass',
 '__builtins__',
 '__doc__',
 '__file__',
 '__name__',
 '__package__',
 '_float',
 '_idmap',
 '_idmapL',
 '_int',
 '_long',
 '_multimap',
 '_re',
 'ascii_letters',
 'ascii_lowercase',
 'ascii_uppercase',
 'atof',
 'atof_error',
 'atoi',
 'atoi_error',
 'atol',
 'atol_error',
 'capitalize',
 'capwords',
 'center',
 'count',
 'digits',
 'expandtabs',
 'find',
 'hexdigits',
 'index',
 'index_error',
 'join',
 'joinfields',
 'letters',
 'ljust',
 'lower',
 'lowercase',
 'lstrip',
 'maketrans',
 'octdigits',
 'printable',
 'punctuation',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rsplit',
 'rstrip',
 'split',
 'splitfields',
 'strip',
 'swapcase',
 'translate',
 'upper',
 'uppercase',
 'whitespace',
 'zfill']

I think you should be able to spot a first clue here...

e-satis