Python不仅支持C风格字符串格式化, 还支持利用format
方法来格式化字符串. format
方法通过占位符{}
来指定参数及参数格式.
指定参数
通过位置指定参数
- 位置索引从0开始
- 可以省略数字
print('{} + {} = 5'.format(2, 3))
print('{0} + {1} = 5'.format(2, 3))
输出:
2 + 3 = 5
2 + 3 = 5
通过名字指定参数
print('I am {name}, in version {version}'.format(name = 'Python', version = 2.7))
输出:
I am Python, in version 2.7
通过.
访问对象的属性
.
会导致对应参数的.getattr()
方法被调用.
class MyCls():
def __init__(self):
self.a = 'a in MyCls'
self.b = 'b in MyCls'
obj = MyCls()
print('{0.a}, {0.b}'.format(obj))
print('{object.a}, {object.b}'.format(object = obj))
输出:
a in MyCls, b in MyCls
a in MyCls, b in MyCls
通过[]
进行索引
[]
会导致对应参数的__getitem__()
方法被调用.
arr = [1, 2, 3]
print('{0[0]}, {0[1]}, {0[2]}'.format(arr))
print('{arr[0]}, {arr[1]}, {arr[2]}'.format(arr = arr))
输出:
1, 2, 3
1, 2, 3
通过!
指定参数的序列化方法
__repr__
与__str__
都可以将对象转化为字符串, 本质上没有区别, 但在意图上有区别: 前者给开发人看, 后者给普通用户看.
* obj!r
调用obj
的__repr__
方法将obj
转化为字符串
* obj!s
调用obj
的__str__
方法将obj
转化为字符串
class MyCls(object):
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'MyCls.__str__: a = {0.a}, b = {0.b}'.format(self)
def __repr__(self):
return 'MyCls.__repr__: a = {0.a}, b = {0.b}'.format(self)
obj = MyCls(1, 2)
print('{0!r}'.format(obj))
print('{0!s}'.format(obj))
输出:
MyCls.__repr__: a = 1, b = 2
MyCls.__str__: a = 1, b = 2
通过:
指定参数的打印格式
指定宽度和对齐方式
# encoding=utf-8
arg = 'content'
print('*' + '{}'.format(arg) + '*') # 根据内容自适应宽度
print('*' + '{:30}'.format(arg) + '*') # 宽度为30, 默认左对齐
print('*' + '{:<30}'.format(arg) + '*') # 宽度为30, 左对齐
print('*' + '{:>30}'.format(arg) + '*') # 宽度为30, 右对齐
print('*' + '{:^30}'.format(arg) + '*') # 宽度为30, 居中
输出:
*content*
*content *
*content *
* content*
* content *
指定填充字符
# encoding=utf-8
arg = 'content'
print('{:*^30}'.format(arg))
输出:
***********content************
指定数字的符号
# encoding=utf-8
print('{:+},{:+}'.format(1, -1)) # 输出数字的符号
print('{:-},{:-}'.format(1, -1)) # 输出负数的符号
print('{: },{: }'.format(1, -1)) # 输出负数的符号, 正数前面加空格
输出:
+1,-1
1,-1
1,-1
指定进制
# encoding=utf-8
print('{:#b}'.format(16)) # 二进制
print('{:#d}'.format(16)) # 十进制, default
print('{:#o}'.format(16)) # 八进制
print('{:#x}'.format(16)) # 十六进制
print('{:#X}'.format(16)) # 十六进制
输出:
0b10000
16
0o20
0x10
0X10
千分位
print('{:,}'.format(100000))
输出:
100,000
使用百分符号, 指数表达方式
# encoding=utf-8
print('In percentage: {:.2%}'.format(0.9))
print('In exponential, i.e., scientific notation: {0:e}, {0:E}'.format(1024))
print('\ngeneral format, 当数值过大或过小时, 自动选择合适的表达方式:')
import numpy as np
print('{0:g}, {0:G}'.format(np.infty))
print('{0:g}, {0:G}'.format(10**15 + 2))
print('{0:g}, {0:G}'.format(10**15 + 2))
print('{0:g}, {0:G}'.format(10**-20))
输出:
In percentage: 90.00%
In exponential, i.e., scientific notation: 1.024000e+03, 1.024000E+03
general format, 当数值过大或过小时, 自动选择合适的表达方式:
inf, INF
1e+15, 1E+15
1e+15, 1E+15
1e-20, 1E-20