用python中字典中的值替换字符串中的值

用python中字典中的值替换字符串中的值,python,dictionary,replace,identifier,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_123a

您能帮我用字典中的值替换标识符值吗。代码如下所示

    #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'

我尝试使用模板模块,但它没有在值中细分。

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

"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

试试这个。因此,我知道要为字典中的每个键替换什么。我认为代码是不言自明的

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

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

>>> import re
>>> to_replace = re.findall('{\d}',s)
>>> to_replace
=> ['{1}', '{2}']
现在通过
替换
值并执行
.replace()

#驱动程序值:

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

您从哪里获得字符串
s
?您是否可以自由更改
s
的格式?能否显示您尝试过的内容以及失败的原因?s来自可随时编辑的属性文件。
IN : s = '${1}_p${guid}s_${2}'
IN : d = {1: 'bob', 2: '123abc', 3: 'CA', 4: 'smith' }