Python str.format

来源:互联网 发布:数据挖掘 关联规则 编辑:程序博客网 时间:2024/06/08 06:33

Python不仅支持C风格字符串格式化, 还支持利用format方法来格式化字符串. format方法通过占位符{}来指定参数及参数格式.

指定参数

通过位置指定参数

  1. 位置索引从0开始
  2. 可以省略数字
print('{} + {} = 5'.format(2, 3))print('{0} + {1} = 5'.format(2, 3))

输出:

2 + 3 = 52 + 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 MyClsa 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, 31, 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 = 2MyCls.__str__: a = 1, b = 2

通过:指定参数的打印格式

这里写图片描述

指定宽度和对齐方式

# encoding=utf-8arg = '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-8arg = 'content'print('{:*^30}'.format(arg))

输出:

***********content************

指定数字的符号

# encoding=utf-8print('{:+},{:+}'.format(1, -1)) # 输出数字的符号print('{:-},{:-}'.format(1, -1)) # 输出负数的符号print('{: },{: }'.format(1, -1)) # 输出负数的符号, 正数前面加空格

输出:

+1,-11,-1 1,-1

指定进制

# encoding=utf-8print('{:#b}'.format(16)) # 二进制print('{:#d}'.format(16)) # 十进制, defaultprint('{:#o}'.format(16)) # 八进制print('{:#x}'.format(16)) # 十六进制print('{:#X}'.format(16)) # 十六进制

输出:

0b10000160o200x100X10

千分位

print('{:,}'.format(100000))

输出:

100,000

使用百分符号, 指数表达方式

# encoding=utf-8print('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 npprint('{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+03general format, 当数值过大或过小时, 自动选择合适的表达方式:inf, INF1e+15, 1E+151e+15, 1E+151e-20, 1E-20

Reference

  • https://docs.python.org/2/library/string.html#format-string-syntax