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)
原文地址:https://www.cnblogs.com/wuheng1991/p/8267637.html