Python__字符串rjust()、ljust() 、center()

str.rjust|ljust|center(width[, fillchar])

1、 rjust() 返回一个原字符串右对齐,ljust() 返回一个原字符串左对齐,center() 返回一个原字符串居中;

a = 'hello world'
def get_str(strs,width,fillchar=' '):
    global a
    print(eval("a.{}({},'{}')".format(strs,width,fillchar)))

get_str('rjust', 22)
get_str('ljust', 22, '*')
get_str('center', 22, '*')

 out:
               hello world
hello world***********
*****hello world******

2、默认填充字符为空格填充至长度 width 的新字符串,如果指定的长度小于原字符串的长度则返回原字符串。

get_str('rjust', 10)
get_str('ljust', 10, '*')
get_str('center', 10, '*')

 out:
hello world
hello world
hello world

3、当center()无法使左右字符数相等时候,字符串字符数为偶数时左侧字符会比右侧多 1,字符串字符数为奇数时左侧字符会比右侧少 1

get_str('center', 14, '*')
a = 'helloworld'
get_str('center', 13, '*')

 out:
*hello world**
**helloworld*

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值