How to pad with n characters in Python

后端 未结 6 795
迷失自我
迷失自我 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'
    
    0 讨论(0)
  • 2020-12-28 13:54
    print '=' * 60
    header = lambda x: '%s%s%s' % ('=' * (abs(int(len(x)) - 60) / 2 ),x,'=' * (abs(int(len(x)) - 60) / 2 ) )
    print header("Bayors")
    
    0 讨论(0)
  • 2020-12-28 13:54

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

    [Ouput]:

    -----------------Hello World-----------------
    Hello World----------------------------------
    ----------------------------------Hello World
    
    0 讨论(0)
  • 2020-12-28 14:04

    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'
    
    0 讨论(0)
  • 2020-12-28 14:09

    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
    
    0 讨论(0)
  • 2020-12-28 14:14

    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.

    0 讨论(0)
提交回复
热议问题