python使用字典格式化字符串-如何在python-3.x中使用字典格式化字符串?

由于Python 3.0和3.1已停产,并且没有人使用它们,因此您可以并且应该使用str.format_map(mapping)(Python 3.2+):

与相似str.format(**mapping),除了直接使用映射而不将其复制到dict。例如,如果映射是dict子类,则这很有用。

这意味着您可以使用例如defaultdict为丢失的键设置(并返回)默认值的a:

>>> from collections import defaultdict

>>> vals = defaultdict(lambda: '', {'bar': 'baz'})

>>> 'foo is {foo} and bar is {bar}'.format_map(vals)

'foo is and bar is baz'

即使提供的映射是dict,而不是子类,也可能会稍快一些。

鉴于给定,差异并不大

>>> d = dict(foo='x', bar='y', baz='z')

然后

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)

大约比10 ns(2%)快

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)

在我的Python 3.4.3上。当字典中有更多键时,差异可能会更大,并且

注意,格式语言比它灵活得多。它们可以包含索引表达式,属性访问等,因此您可以格式化整个对象或其中两个:

>>> p1 = {'latitude':41.123,'longitude':71.091}

>>> p2 = {'latitude':56.456,'longitude':23.456}

>>> '{0[latitude]} {0[longitude]} - {1[latitude]} {1[longitude]}'.format(p1, p2)

'41.123 71.091 - 56.456 23.456'

从3.6开始,您也可以使用插值字符串:

>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'

'lat:41.123 lng:71.091'

您只需要记住在嵌套引号中使用其他引号字符。这种方法的另一个好处是,它比调用格式化方法要快得多。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值