python 字符串怎么补零到规定位数

'''
原字符串左侧对齐, 右侧补零:
'''
str.ljust(width,'0')
input: '789'.ljust(32,'0')
output: '78900000000000000000000000000000'


'''
原字符串右侧对齐, 左侧补零:
方法一:
'''
str.rjust(width,'0')
input: '798'.rjust(32,'0')
output: '00000000000000000000000000000798'
'''
方法二:
'''
str.zfill(width)
input: '123'.zfill(32)
output:'00000000000000000000000000000123'
'''
方法三:
'''
'%07d' % n
input: '%032d' % 89
output:'00000000000000000000000000000089'

示例

def xyz_to_msg(x : int,y : int,z : int) -> str:

   assert len(str(x)) <= 5, 'The length of x cannot be greater than 5!'
   assert len(str(y)) <= 5, 'The length of y cannot be greater than 5!'
   assert len(str(z)) <= 5, 'The length of z cannot be greater than 5!'

   msg_x = str(x).rjust(5,'0') if x > 0 else '-' + str(-x).rjust(4,'0')
   msg_y = str(y).rjust(5,'0') if y > 0 else '-' + str(-y).rjust(4,'0')
   msg_z = str(z).rjust(5,'0') if z > 0 else '-' + str(-z).rjust(4,'0')
   msg = msg_x + msg_y + msg_z
   return  msg
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值