python字符串调用函数和参数_【Python】字符串格式化调用方法

一、基础知识

str.format()的使用语法

在主体字符串(string)中,花括号通过位置(例如,{1})或关键字(例如,{food})指出替换目标及将要插入的参数。

该方法创建并返回一个新的字符串对象,可以被立即打印或保存起来。

例如:

template = '{0}, {1} and {2}'

template.format('spam', 'ham', 'eggs')

# spam, ham and eggs

template = '{motto}, {pork} and {food}'

template.format(motto = 'spam', pork = 'ham', food = 'eggs')

# spam, ham and eggs

template = '{motto}, {0} and {food}'

template.format('ham', motto = 'ham', food = 'eggs')

主体字符串也可以是一个临时字符串常量,并且任意的对象类型都可以替换。

'{motto}, {0} and {food}'.format(42, motto=3.14, food = [1,2])

# '3.14, 42 and [1,2]'

二、添加键,属性和偏移量

格式化字符串可以指定对象属性和字典键:方括号指定字典键,点表示位置或关键字所引用的一项的对象属性

>>> import sys

>>> '{1[spam]} and {0.platform}'.format(sys, {'spam':'laptop'})

out: laptop and win32

>>> '{config[spam]} and {sys.platform}'.format(sys = sys, config = {'spam':'laptop'})

out: laptop and win32

格式化字符串中的方括号可以指定列表(及其他序列)的(正)偏移量以执行索引

>>> somelist = list('SPAM') # ['S', 'P', 'A', 'M']

>>> 'first = {0[0]} and second = {0[1]}'.format(somelist)

out: first = S and second = P

三、添加具体格式化

str.format()的替代目标语法

形式化结构:{fieldname!conversionflag:formatspec}

fielname 是指定参数的一个数字或关键字,后面跟着可选的“.name”或“[index]”成分引用

conversionflag 可以是r, s, 或者a分别是在该值上对rper, str 或ascii内置函数的一次调用

formatspec 指定了如何表示该值,包括字段宽度,对齐方式,补零,小数点精度等细节,并且以一个可选的数据类型编码结束。

formatspec 组成形式如下:

[[fill]align][sign][#][0][width][.precision][typecode]

align 可能是>,

formatspec 也包含嵌套的,只带有{}的格式化字符串,它从参数列表动态地获取值

一些常见示例如下:

>>> '{0:10} = {1:10}'.format('spam', 123.456) # 第一个位置参数,10个字符宽

out: 'spam = 123.456'

>>> '{0:>10} = {1:<10}'.format('spam', 123.456) # 第一个位置参数右对齐,10个字符宽;第二个位置参数左对齐,10个字符宽

out:' spam = 123.456 '

>>> '{0.platform:>10} = {1[item]:<10}'.format(sys, dict(item='laptop'))

out:' win32 = laptop '

浮点数代码示例如下:

>>> '{0:e}, {1:.3e}, {2:g}'.format(3.14159, 3.14159, 3.14159)

out: 3.141590e+00, 3.142e+00, 3.14159

>>> '{0:f}, {1:.2f}, {2:06.2f}'.format(3.14159, 3.14159, 3.14159)

out: 3.141590, 3.14, 003.14

# {2:g} 表示第三个参数默认根据“g”浮点数表示格式化

# {1:.2f}指定了带有2个小数位的“f”浮点数格式

# {2:06.2f}添加一个6字符宽的字段并且在左边补充0

嵌套式格式化语法,从参数列表动态地获取

>>> '{0:.{1}f}'.format(1/3.0, 4)

out: 0.3333

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值