How to pad with n characters in Python

后端 未结 6 798
迷失自我
迷失自我 2020-12-28 13:29

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\'

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 13:53

    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'
    

提交回复
热议问题