format方法被用于字符串的格式化输出。

 print('{0}+{1}={2}'.format(1,2,1+2))   #in
1+2=3   #out

可见字符串中大括号内的数字分别对应着format的几个参数。

若省略数字:

print('{}+{}={}'.format(1,2,1+2))   #in

可以得到同样的输出结果。但是替换顺序默认按照[0],[1],[2]...进行。

若替换{0}和{1}:

print('{1}+{0}={2}'.format(1,2,1+2))   #in
2+1=3   #out

输出字符串:

print('{0} am {1}'.format('i','alex'))  
i am alex   #out

输出参数的值:

 length = 4
name = 'alex'
print('the length of {0} is {1}'.format(name,length))
the length of alex is 4

精度控制:

print('{0:.3}'.format(1/3))
0.333

宽度控制:

print('{0:7}{1:7}'.format('use','python'))
use    python 

精宽度控制(宽度内居左):

print('{0:<7.3}..'.format(1/3))   
0.333  ..

其实精宽度控制很类似于C中的printf函数。

同理'>'为居右,'^'为居中。符号很形象。

补全:

 #!/usr/bin/python
#python3.6
print('{0:0>3}'.format(1)) #居右,左边用0补全
print('{0:{1}>3}'.format(1,0)) #也可以这么写
#当输出中文使用空格补全的时候,系统会自动调用英文空格,这可能会造成不对齐
#for example
blog = {'':'中国石油大学','':'浙江大学','':'南京航空航天大学'}
print('不对齐:')
print('{0:^4}\t\t{1:^8}'.format('序号','名称'))
for no,name in blog.items(): #字典的items()方法返回一个键值对,分别赋值给no和name
print('{0:^4}\t\t{1:^8}'.format(no,name))
print('\n对齐:')
print('{0:^4}\t\t{1:{2}^8}'.format('序号','名称',chr(12288))) #chr(12288)为UTF-8中的中文空格
for no,name in blog.items():
print('{0:^4}\t\t{1:{2}^8}'.format(no,name,chr(12288)))
#out
001
001
不对齐:
序号 名称
1 中国石油大学
2 浙江大学
3 南京航空航天大学 对齐:
序号    名称   
1  中国石油大学 
2   浙江大学  
3 南京航空航天大学

最新文章

  1. 使用html和css的一些经验
  2. 【转】Mysql中varchar存放中文与英文所占字节异同
  3. Machine Learning 学习笔记 (3) —— 泊松回归与Softmax回归
  4. Z-Stack内部API 小结
  5. web容器线程数和程序中线程阻塞导致 请求超时
  6. 团队作业4--第一次项目冲刺(Alpha版本) 5
  7. Centos下安装Mysql异常
  8. @property的使用
  9. .net core2 单元测试
  10. VC++安装及使用
  11. OSI七层模型和TCP/IP四层模型
  12. CATransaction(参考其他博客敲)
  13. 发布Asp.net core到nginx 使用nginx代理
  14. 探寻main函数的“标准”写法,以及获取main函数的参数、返回值
  15. 【总结】牛客职播第九期:您的美团点评offer已送到门口,快来与我们一起影响世界!
  16. for练习相关
  17. 使用eclipse在linux下开发C/C++
  18. Palindrome Number - LeetCode
  19. bzoj2755【SCOI2012】喵星人的入侵
  20. Mysql 关于not exists一例

热门文章

  1. buildroot管理uboot+kernel+rootfs
  2. inno安装客户端,写注册表url调用客户端
  3. java 你画我猜 了解一下
  4. 2. Packet crafting tools (封包工具 6个)
  5. Spark:将DataFrame写入Mysql
  6. [工作积累] UE4 并行渲染的同步 - Sync between FParallelCommandListSet &amp; FRHICommandListImmediate calls
  7. impdp如何杀掉job
  8. KiCad EDA 原理图库的最佳实践
  9. python之 自动补全 tab
  10. javascript中的立即执行函数的原理