python内置函数之format()

str.format() 是python的一种新型字符串格式化函数,通过‘{}’和‘:’替代之前的‘%’字符串格式化方法。

具体方法如下

A.通过位置传递变量

print('{0},{1},{2}'.format('Mercury','Earth','Mars'))
Mercury,Earth,Mars
print('{2},{1},{0}'.format('Mercury','Earth','Mars'))
Mars,Earth,Mercury
print('{0},{0},{0}'.format('Mercury','Earth','Mars'))
Mercury,Mercury,Mercury
print('{}{}'.format('Mar','s'))
Mars

B.通过变量名称传递变量

print('Beijing_position:{East,West}'.format(East='116°E',West='39°N'))
Beijing_position:116°E,39°N

C.传递变量的字段item

a = (2021,2)
print('year:{0[0]},month:{0[1]}'.format(a))
year:2021,month:2

D.替代%r与%s

使用%的字符串格式化:

print("repr() shows quotes: %r; str() doesn't: %s" % ('test1', 'test2'))
repr() shows quotes: 'test1'; str() doesn't: test2

使用format的字符串格式化:

print("repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2'))
repr() shows quotes: 'test1'; str() doesn't: test2

E.校准输出内容并控制长度

print('{:<10}'.format('Mars'))#长度10个空格,右侧默认空格补齐
Mars      
print('{:>10}'.format('Mars'))#长度10个空格,左侧默认空格补齐
      Mars
print('{:^10}'.format('Mars'))#长度居中
   Mars   
   
print('{:!^10}'.format('Mars'))#填充!或*
!!!Mars!!!
print('{:*^10}'.format('Mars'))
***Mars***

print('{:,}'.format(2131241242))#使用‘,’分割三位数字
2,131,241,242

print('{:!^20,}'.format(141241241))#综合运用
!!!!141,241,241!!!!!

F.用于数字格式化

#浮点数保留位数系列
a = 3.1415926
print('{:.2f}'.format(a))#保留小数点后两位
print('%.2f' % a) #使用‘%’进行格式化与format对比
3.14
3.14
print('{:+.2f}'.format(a))#带有正负号保留小数点后两位
+3.14
print('{:.0f}'.format(a))#取整数,四舍五入
3
#填充系列
a = 3
print('{:x<5d}'.format(a))#右填充‘x’
3xxxx
print('{:y<5d}'.format(a))#右填充‘y’
3yyyy
print('{:z>5d}'.format(a))#左填充‘z’
zzzz3
#百分数
print('{:.3%}'.format(a))#
300.000%

附字符串常用方法:

str.upper()用于大写
str.lower()用于小写
str.split()用于分割字符返回一个列表
str.strip()用于去除指定字符
str.join()用于添加字符
str.find()找到指定字符
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值