分为两种,分别为占位符(%)和format方式。占位符方式在Python2.x中用的比较广泛,随着Python3.x的使用越来越广,format方式使用的更加广泛。
一、占位符
# -*- coding: UTF-8 -*-
from __future__ import print_function
print ("%s's score is %d" % ('Mike', 87))
Mike's score is 87
*注:3.x情况下为上图,在2.x情况下,为print "%s's score is %d" % ('Mike', 87)
二、format
位置映射
实例(Python3.0+):
1 2 |
|
关键字映射
实例(Python3.0+):
1 2 |
|
元素访问
实例(Python3.0+):
1 2 |
|
填充对齐
- ^、<、>分别是居中、左对齐、右对齐
实例1(Python3.0+):
1 2 3 4 5 |
|
实例2(Python3.0+):九九乘法表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
小练习:
print("{1[0]},{0[1]}".format((1,0),(2,9)))
2,0
>>> print("{0}*{1}={2:0>2}".format(3,2,2*3))
3*2=06
>>> print("{0}*{1}={2:>2}".format(3,2,2*3))
3*2= 6
>>> print("{0}*{1}={2:>}".format(3,2,2*3))
3*2=6
>>> print("{0}*{1}={2>}".format(3,2,2*3))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: '2>'
精度设置
实例(Python3.0+):
1 2 3 4 |
|