python之字符串格式化(format)

本文详细介绍了Python中字符串格式化的方法,包括位置参数、关键字参数的使用,填充与格式化技巧,以及数字格式化的多种方式。并通过具体示例展示了如何进行字符串格式化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、使用位置参数

要点:从以下例子可以看出位置参数不受顺序约束,且可以为{},只要format里有相对应的参数值即可,参数索引从0开,传入位置参数列表可用*列表

复制代码
>>> li = ['hoho',18]
>>> 'my name is {} ,age {}'.format('hoho',18)
'my name is hoho ,age 18'
>>> 'my name is {1} ,age {0}'.format(10,'hoho')
'my name is hoho ,age 10'
>>> 'my name is {1} ,age {0} {1}'.format(10,'hoho')
'my name is hoho ,age 10 hoho'
>>> 'my name is {} ,age {}'.format(*li)
'my name is hoho ,age 18'
复制代码

 

2、使用关键字参数

要点:关键字参数值要对得上,可用字典当关键字参数传入值,字典前加**即可

>>> hash = {'name':'hoho','age':18}
>>> 'my name is {name},age is {age}'.format(name='hoho',age=19)
'my name is hoho,age is 19'
>>> 'my name is {name},age is {age}'.format(**hash)
'my name is hoho,age is 18'

 

3、填充与格式化

:[填充字符][对齐方式 <^>][宽度]

>>> '{0:*>10}'.format(10)  ##右对齐
'********10'
>>> '{0:*<10}'.format(10)  ##左对齐
'10********'
>>> '{0:*^10}'.format(10)  ##居中对齐
'****10****'

 

4、精度与进制

复制代码
>>> '{0:.2f}'.format(1/3)
'0.33'
>>> '{0:b}'.format(10)    #二进制
'1010'
>>> '{0:o}'.format(10)     #八进制
'12'
>>> '{0:x}'.format(10)     #16进制
'a'
>>> '{:,}'.format(12369132698)  #千分位格式化
'12,369,132,698'
复制代码

 

5、使用索引

>>> li
['hoho', 18]
>>> 'name is {0[0]} age is {0[1]}'.format(li)
'name is hoho age is 18

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

实例

>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置'world hello world'

也可以设置参数:

实例

#!/usr/bin/python# -*- coding: UTF-8 -*- print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com")) # 通过字典设置参数site = {"name": "菜鸟教程", "url": "www.runoob.com"}print("网站名:{name}, 地址 {url}".format(**site)) # 通过列表索引设置参数my_list = ['菜鸟教程', 'www.runoob.com']print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的

输出结果为:

网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com

也可以向 str.format() 传入对象:

实例

#!/usr/bin/python# -*- coding: UTF-8 -*- class AssignValue(object): def __init__(self, value): self.value = valuemy_value = AssignValue(6)print('value 为: {0.value}'.format(my_value)) # "0" 是可选的

输出结果为:

value 为: 6

数字格式化

下表展示了 str.format() 格式化数字的多种方法:

>>> print("{:.2f}".format(3.1415926));
3.14
数字格式输出描述
3.1415926{:.2f}3.14保留小数点后两位
3.1415926{:+.2f}+3.14带符号保留小数点后两位
-1{:+.2f}-1.00带符号保留小数点后两位
2.71828{:.0f}3不带小数
5{:0>2d}05数字补零 (填充左边, 宽度为2)
5{:x<4d}5xxx数字补x (填充右边, 宽度为4)
10{:x<4d}10xx数字补x (填充右边, 宽度为4)
1000000{:,}1,000,000以逗号分隔的数字格式
0.25{:.2%}25.00%百分比格式
1000000000{:.2e}1.00e+09指数记法
13{:10d}        13右对齐 (默认, 宽度为10)
13{:<10d}13左对齐 (宽度为10)
13{:^10d}    13中间对齐 (宽度为10)
11
'{:b}'.format(11)
'{:d}'.format(11)
'{:o}'.format(11)
'{:x}'.format(11)
'{:#x}'.format(11)
'{:#X}'.format(11)
1011
11
13
b
0xb
0XB
进制

^<> 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

+ 表示在正数前显示 +,负数前显示 -  (空格)表示在正数前加空格

b、d、o、x 分别是二进制、十进制、八进制、十六进制。

此外我们可以使用大括号 {} 来转义大括号,如下实例:

实例

#!/usr/bin/python# -*- coding: UTF-8 -*- print ("{} 对应的位置是 {{0}}".format("runoob"))

输出结果为:

runoob 对应的位置是 {0}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值