python基础——format()函数详解

format()函数格式化的详细使用

format(a,b,…,*args,**kwargs):

​ 其中参数的类型是str类型

格式{:}.format(a,b,…,*args,**kwargs) :

​ 冒号左边填format函数传入的参数对应的位置下标,冒号右边是对:冒号左边传入的参数的约束,下面详解冒号右边的约束内容和一些其他常用方法


  • 位置填充
  1. 如果占位符中有顺序标记,填充时应按照填充对象的 顺序索引来填充
#示例:		
		a= 'hello{0},欢迎来到{1}'
        a= 'hello{1},欢迎来到{0}'
        print(a.format('lsg','python'))
        
#运行结果:
hello lsg,欢迎来到python
hello python,欢迎来到lsg         
  1. 如果占位符中不写任何参数,则默认按照填充对象的 依次顺序填充
#示例:
		a= 'hello {},欢迎来到{}'
		print(a.format('lsg','python'))	
		
#运行结果:
hello lsg,欢迎来到python
  • 关键字(key)填充
#示例
1.
    a = 'hello {name}, welcome to {skill}'
    print(a.format(name = 'lsg',skill = 'python'))
2.
	lsgPy = {'name':'lsg','skill':'python'}
	a = 'hello {key[name]}, welcome to {key[skill]}'
	print(a.format(key = lsgPy))
	
#运行结果
1.
hello lsg, welcome to python
2.
hello lsg, welcome to python
  • 序列(str,list,tuple)的下标填充(与位置填充可以混合使用)
#示例
1.
    lsgPy1 = ['lsg','python']
    lsgPy2 = ['lsg','python']
    a = 'hello {0[0]}, welcome to {0[1]}'
    print(a.format(lsgPy1))
    print(a.format(lsgPy2))  
2.
	lsgPy = ['lsg','python']
    qwPy = ['qw','java']
    a = 'hello {0[0]}, welcome to {0[1]}!\n' \
    'hello {1[0]}, welcome to {1[1]}!'
	b = 'hello {1[0]}, welcome to {1[1]}!\n' \
    'hello {0[0]}, welcome to {0[1]}!'
    print(a.format(lsgPy,qwPy))
    print('*'*40)
    print(b.format(lsgPy,qwPy))

#运行结果
1.
hello lsg, welcome to python

2.
hello lsg, welcome to python!
hello qw, welcome to java!
****************************************
hello qw, welcome to java!
hello lsg, welcome to python!
  • 输出填充与对齐
格式含义
{:x>y}左填充x(x可以是键盘上任何 单个字符),宽度为y (y为填充后的整体宽度)
{:x<y}右填充,规则同上(y如果小于format函数中填入的参数的长度,则不进行填充)
{: x^y}两边填充,规则同上
{:>y}右对齐,宽度为y,在目标字符前填充空格
{:<y}左对齐,宽度为y,在目标字符前填充空格(系统默认:若不写对齐符号,系统默认左对齐)
{:^y}居中对齐,宽度为y,两边填充
#示例
        print('{:>5}'.format(3))
        print('{:d>6}'.format(4))
        print('{:-<5}'.format('s'))
        print('{:-<5}'.format(123456))
        print('{:-<5}'.format(123))
        print('{:-^5}'.format(3))
        print('{: >8}'.format('lsg'))
        print('{: <8}'.format('lsg'))
        print('{: ^8}'.format('lsg'))
        print('{:8}'.format('lsg'))

#运行结果
    3
ddddd4
s----
123456
123--
--3--
     lsg
lsg     
  lsg   
lsg     
  • 数字字符串格式化
格式含义
{m.n}.formatm.n格式
{:.5f}保留两五小数,如果小数位数超过5位,则第6位小数会四舍五入进第五位
{:+.5f}带符号的保留五位小数
{:.0f}不带小数
{:.n%}格式化成小数点后含有n位的百分数
{:.ne}科学计数
{:b}转化为二进制
{:d}转化为十进制
{:o}转化为八进制
{:x}转化为十六进制
#示例
        print('{:.5f}'.format(12))
        print('{:+.5f}'.format(12))
        print('{:.0f}'.format(12.32))
        print('{:+.2f}'.format(12.1274))
        print('{:.1%}'.format(0.34586))
        print('{:.3e}'.format(1234))
        print('{:b}'.format(6))
        print('{:d}'.format(18))
        print('{:o}'.format(18))
        print('{:x}'.format(18))

#运行结果
12.00000
+12.00000
12
+12.13
34.6%
1.234e+03
110
18
22
12
  • 转义字符
#示例
        print('{{}}..'.format('lsg'))
        print('{{lsg}}..'.format('lsg'))
        print('{{ hello {0},welcome to {1} }}..' \
                .format('lsg','python'))
        print('{{ {:-^6} }}'.format('lsg'))
        print('{{ lsg {{hello}} }}'.format())
        
#运行结果
{}..
{lsg}..
{ hello lsg,welcome to python }..
{ -lsg-- }
{ lsg {hello} }

#注
1. 其中{{}}相当于转义字符输出{},并且内层{}两边不能有空,外层{}相当于转义字符
2. {{lsg}}在从外数第二层{}内的所有字符会原样输出 
3. 在{{ {} }}最内层{}才是真正的占位符,用来输出format函数传入的参  数
4. {}必须成对出现,内层嵌套也是成对出现,单个出现会报错
  • 内嵌{}使用
#示例
     print('hello {0:{2}},welcome to {1:>{3}} '\
          .format('lsg','python',3,4))
          
#运行结果
hello lsg,welcome to python  

#注
1. {:{}}冒号右边的占位符{}中传入的format参数必须是数字字符,这里本质是宽度
  • 格式化时间
#示例
        from datetime import datetime
        now=datetime.now()
        print('{:%Y--%m--%d--%X}'.format(now))
        
#运行结果
2019--09--07--23:28:09
  • 7
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`format()` 函数Python 中用于字符串格式化的方法。它允许将一个或多个值插入到一个字符串中的指定位置,生成一个新的字符串。 `format()` 函数的语法如下: ```python string.format(value1, value2, ...) ``` 其中,`string` 是要格式化的字符串,`value1`, `value2`, ... 是要插入到字符串中的值。 `format()` 函数使用方法有多种,下面介绍其中的一些常用方式: - 位置参数:通过使用花括号 `{}` 和位置参数的形式,可以将值插入到指定的位置。 ```python "我叫 {}, 今年 {} 岁。".format("小明", 18) # 输出:我叫 小明, 今年 18 岁。 ``` - 关键字参数:通过使用花括号 `{}` 和关键字参数的形式,可以将值插入到指定的位置。 ```python "我叫 {name}, 今年 {age} 岁。".format(name="小明", age=18) # 输出:我叫 小明, 今年 18 岁。 ``` - 数字索引:通过使用花括号 `{}` 和数字索引的形式,可以将值插入到指定的位置。 ```python "我叫 {0}, 今年 {1} 岁。".format("小明", 18) # 输出:我叫 小明, 今年 18 岁。 ``` - 格式化类型:可以通过在花括号 `{}` 中使用冒号 `:` 来指定格式化类型。常用的格式化类型包括: - `d`:整数类型。 - `f`:浮点数类型。 - `e`:科学计数法类型。 - `s`:字符串类型。 例如: ```python "我的成绩是 {:.1f} 分。".format(89.1234) # 输出:我的成绩是 89.1 分。 ``` `format()` 函数还支持更复杂的格式化方式,例如使用字典作为参数、嵌套使用等。详细使用方式可以参考官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值