用python中的字典中的值替换string中的值

时间:2017-10-24 15:51:20

标签: python dictionary replace identifier

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

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

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

   output = 'bob_p${guid}s_123abc'

我尝试使用模板模块,但它没有加入值。

3 个答案:

答案 0 :(得分:1)

使用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 values:

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

答案 1 :(得分:0)

试试这个。所以,我知道要替换字典中的每个键。我认为代码是自我解释的。

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

for i in d:
    s = s.replace('${'+str(i)+'}',d[i])
print(s)

输出:

bob_p${guid}s_123abc

答案 2 :(得分:-2)

您可以使用标准字符串.format()方法。 Here是指向相关信息的文档的链接。您可能会发现页面中的以下引用特别有用。

"First, thou shalt count to {0}"  # References first positional argument
"Bring me a {}"                   # Implicitly references the first positional argument
"From {} to {}"                   # Same as "From {0} to {1}"
"My quest is {name}"              # References keyword argument 'name'
"Weight in tons {0.weight}"       # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}"   # First element of keyword argument 'players'.

以下是基于使用.format()方法修改的代码。

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

s = ''
try:
    s = '{0[1]}_p'.format(d) + '${guid}' + 's_{0[2]}'.format(d)
except KeyError:
    # Handles the case when the key is not in the given dict. It will keep the sting as blank. You can also put
    # something else in this section to handle this case. 
    pass
print s