Python 第16課 字串格式化2 Crossin的程式設計教室
分為兩種,分別為佔位符(%)和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 |
|