本文介绍了用python中的字典中的值替换字符串中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能协助我用字典中的值替换标识符值吗?所以代码看起来像是

Could you assist me with replacing an identifier value with a value from a dictionary. So the code looks like follow

    #string holds the value we want to output
    s = '${1}_p${guid}s_${2}'
    d = {1: 'bob', 2: '123abc', 3: 'CA', 4: 'smith' }

我希望能够将$ {1}替换为bob,将$ {2}替换为123abc,我只想更改$ {}中的值只是一个数字的值,然后将其替换为词典.

I want to be able to replace ${1} with bob and ${2} with 123abc, I only want to change a value if the value inside ${} is just a number then, replace it with the value within the dictionary.

   output = 'bob_p${guid}s_123abc'

我尝试使用模板模块,但是它没有包含在值中.

I tried using template module, but it did not sub in the value.

推荐答案

使用 re.findall 获取要替换的值.

>>> import re
>>> to_replace = re.findall('{\d}',s)
>>> to_replace
=> ['{1}', '{2}']

现在通过 to_replace 值执行 .replace().

>>> for r in to_replace:
        val = int(r.strip('{}'))
        try:                                     #since d[val] may not be present
               s = s.replace('$'+r, d[val])
        except:
               pass

>>> s
=> 'bob_p${guid}s_123abc'

#driver值:

IN : s = '${1}_p${guid}s_${2}'
IN : d = {1: 'bob', 2: '123abc', 3: 'CA', 4: 'smith' }

这篇关于用python中的字典中的值替换字符串中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 11:47