python中format函数用法简书_Python格式化字符串format

0. 测试环境

Python 3.6.9

1. 引言

Python中格式化字符串的方式有,一种是用%操作符来进行字符串格式化,一种是使用str.format()来进行字符串格式化,本文主要介绍str.format()方式,这种方式更主流,也是官方推荐的方式,%的方式后面会逐渐淘汰。

2. 格式化字符串

2.1 基本语法

格式化字符串包含用大括号{}括起来的“替换字段”,。大括号中不包含的内容被视为正常文本,会原样输出。注意:如果要在文本中输出大括号,需要使用{{和}}来转义,不是使用场景的转义字符\。示例如下:

>>> 'This is a format {}.'.format('test')

'This is a format test.'

>>> 'This is {{}} test.'.format()

'This is {} test.'

下面是“替换字段”的语法,后面的示例中会具体讲到:

replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"

field_name ::= arg_name ("." attribute_name | "[" element_index "]")*

arg_name ::= [identifier | digit+]

attribute_name ::= identifier

element_index ::= digit+ | index_string

index_string ::= +

conversion ::= "r" | "s" | "a"

format_spec ::=

2.2 位置参数标识符

格式化字符串中,默认情况下{}中可以不加位置标识符,即'{} {}'.format(a, b)与'{0} {1}'.format(a, b)是等价的,但如果位置标识符在字符串中不是按参数顺序出现的,则需要显示的指明位置标识符。示例代码如下:

>>> '{0} {1}'.format('one', 'two')

'one two'

>>> '{} {}'.format('one', 'two')

'one two'

>>> '{1} {0}'.format('one', 'two')

'two one'

>>> '{0} {1} {0}'.format('one', 'two')

'one two one'

2.3 设置参数

格式化字符串中可以使用变量、字典、列表索引、类的属性等来设置参数。示例代码如下:

print('Name: {name}, URL: {url}'.format(name='Tyan', url='http://noahsnail.com'))

name = 'Tyan'

url = 'http://noahsnail.com'

print('Name: {}, URL: {}'.format(name, url))

site = {'name' : 'Tyan', 'url' : 'http://noahsnail.com'}

print('Name: {site[name]}, URL: {site[url]}'.format(site=site))

print('Name: {name}, URL: {url}'.format(**site))

site = ['Tyan', 'http://noahsnail.com']

print('Name: {0[0]}, URL: {0[1]}'.format(site))

class Test(object):

def __init__(self):

self.name = 'Tyan'

self.url = 'http://noahsnail.com'

print('Name: {0.name}, URL: {0.url}'.format(Test()))

site = {'name' : 'Tyan', 'url' : 'http://noahsnail.com'}

print('Name: {name}, URL: {url}'.format(**site))

# Output

Name: Tyan, URL: http://noahsnail.com

Name: Tyan, URL: http://noahsnail.com

Name: Tyan, URL: http://noahsnail.com

Name: Tyan, URL: http://noahsnail.com

Name: Tyan, URL: http://noahsnail.com

Name: Tyan, URL: http://noahsnail.com

Name: Tyan, URL: http://noahsnail.com

2.3 转换标志(conversion)

转换标志以!开始,主要有三种!s、!r、!a,分别会调用参数对象的__str__,__repr__,__ascii__方法。

class Test(object):

def __str__(self):

return 'Test str function.'

def __repr__(self):

return 'Test repr function.'

def __ascii__(self):

return 'Test ascii function.'

print('str: {t!s}, repr: {t!r}, ascii: {t!a}'.format(t=Test()))

# Ouput

str: Test str function., repr: Test repr function., ascii: Test repr function.

2.4 格式化说明(format_spec)

格式化说明包含了值表示的说明,包括字段宽度、对其方式、填充、小数准确率等,其以:开头。标准格式化说明符的一般形式为:

format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]

fill ::=

align ::= "<" | ">" | "=" | "^"

sign ::= "+" | "-" | " "

width ::= digit+

grouping_option ::= "_" | ","

precision ::= digit+

type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

<表示输出结果左对齐,>是右对齐,^是居中对其,=表示填充值在符号之后数字之前,例如+00001234。

+表示正负数字都要带符号,-表示只有负数需要带负号,表示正数前面带空格,负数前面带负号。

数字表示。b表示二进制格式,c表示将整数转换为字符,d表示十进制整数,o表示八进制格式,x,X表示十六进制格式,x大于9的字母为小写,X大于9的字母为大写。默认为d。

其它说明符的具体解释可参考文档[1]。

示例及结果如下:

print('{:<8}'.format('1234'))

print('{:>8}'.format('1234'))

print('{:^8}'.format('1234'))

print('{:*>8}'.format('1234'))

print('{:*<8}'.format('1234'))

print('{:*^8}'.format('1234'))

print('{:+f}; {:+f}'.format(3.14, -3.14))

print('{: f}; {: f}'.format(3.14, -3.14))

print('{:-f}; {:-f}'.format(3.14, -3.14))

print('int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}'.format(100))

print('int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}'.format(100))

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

print('{:.2e}'.format(100000000))

print('percentage: {:.2%}'.format(1 / 3))

import datetime

print('{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))

# Output

1234

1234

1234

****1234

1234****

**1234**

+3.140000; -3.140000

3.140000; -3.140000

3.140000; -3.140000

int: 100; hex: 64; oct: 144; bin: 1100100

int: 100; hex: 0x64; oct: 0o144; bin: 0b1100100

100,000,000

1.00e+08

percentage: 33.33%

2020-06-18 19:36:38

References

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值