开发者

How to pad with n characters in Python

开发者 https://www.devze.com 2023-01-20 23:40 出处:网络
I should define a function pad_wi开发者_如何学编程th_n_chars(s, n, c) that takes a string \'s\', an integer \'n\', and a character \'c\' and returns

I should define a function pad_wi开发者_如何学编程th_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".


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'

Using f-string: f'{"dog":x^5}'


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


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.


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


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'


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

精彩评论

暂无评论...
验证码 换一张
取 消