python的字符串格式化%s %-2s

string="hello"  
  
#%s打印时结果是hello  
print "string=%s" % string      # output: string=hello  
  
#%2s意思是字符串长度为2,当原字符串的长度超过2时,按原长度打印,所以%2s的打印结果还是hello  
print "string=%2s" % string     # output: string=hello  
  
#%7s意思是字符串长度为7,当原字符串的长度小于7时,在原字符串左侧补空格,  
#所以%7s的打印结果是  hello  
print "string=%7s" % string     # output: string=  hello  
  
#%-7s意思是字符串长度为7,当原字符串的长度小于7时,在原字符串右侧补空格,  
#所以%-7s的打印结果是  hello  
print "string=%-7s!" % string     # output: string=hello  !  
  
#%.2s意思是截取字符串的前2个字符,所以%.2s的打印结果是he  
print "string=%.2s" % string    # output: string=he  
  
#%.7s意思是截取字符串的前7个字符,当原字符串长度小于7时,即是字符串本身,  
#所以%.7s的打印结果是hello  
print "string=%.7s" % string    # output: string=hello  
  
#%a.bs这种格式是上面两种格式的综合,首先根据小数点后面的数b截取字符串,  
#当截取的字符串长度小于a时,还需要在其左侧补空格  
print "string=%7.2s" % string   # output: string=     he  
print "string=%2.7s" % string   # output: string=hello  
print "string=%10.7s" % string  # output: string=     hello  
  
#还可以用%*.*s来表示精度,两个*的值分别在后面小括号的前两位数值指定  
print "string=%*.*s" % (7,2,string)      # output: string=     he  

原文地址https://blog.csdn.net/qq_37482544/article/details/63720726

  • 8
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值