Python中print格式化输出

截取字符串输出,下面例子将只输出字符串的前3个字母      
>>> str="abcdefg"  
>>> print "%.3s" % str   
  abc   
按固定宽度输出,不足使用空格补全,下面例子输出宽度为10      
>>> str="abcdefg"  
>>> print "%10s" % str   
     abcdefg   
截取字符串,按照固定宽度输出      
>>> str="abcdefg"  
>>> print "%10.3s" % str   
         abc   

测试用例:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

str = "abcdefg"
print("%.3s"%str)

# dec = 123.567
# print("%.2d"%dec)
print("%8s"%str)

print("%8.2s"%str)

 

posted @ 2018-01-11 11:47  侠岚之弋痕夕  阅读(1267)  评论(0编辑  收藏  举报
Where is the starting point, we don't have a choice, but the destination where we can pursue!