python 批量替换字符串 根据字典_python – 使用字典的字符串替换

作为一种更通用的方法,您可以使用具有适当替换功能的re.sub:

>>> d={'key1':'string','key2':'placeholders'}

>>> re.sub(r'\$\[([^\]]*)\]',lambda x:d.get(x.group(1)),msg)

'This string contains custom placeholders'

使用正则表达式的优点是它拒绝匹配不具有预期格式的字符串中的占位符字符!

或者作为一种更简单的方法,您可以使用以下字符串格式:

In [123]: d={'key1':'string','key2':'placeholders'}

...: msg='This {key1} contains custom {key2}'

...:

...:

In [124]: msg.format(**d)

Out[124]: 'This string contains custom placeholders'

或者如果你的变量数量不是那么大,你可以将你的密钥作为当前命名空间中可访问的变量,而不是使用字典,然后使用自Python-3.6以来引入的f字符串:

In [125]: key1='string'

...: key2= 'placeholders'

...: msg=f'This {key1} contains custom {key2}'

...:

In [126]: msg

Out[126]: 'This string contains custom placeholders'

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值