How to pad with n characters in Python

后端 未结 6 829
迷失自我
迷失自我 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: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
    

提交回复
热议问题