Python str.format

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

指定参数

通过位置指定参数

  1. 位置索引从0开始
  2. 可以省略数字
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

Reference

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值