Replacing a value in string with a value in a dictionary in python

依然范特西╮ 提交于 2021-01-28 06:51:26

问题


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

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.


回答1:


Use re.findall to get the values to be replaced.

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

Now go through the to_replace values and perform .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' }



回答2:


Try this. So, I know what to replace for each key in the dictionary. I think the code is self explanatory.

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)

Output:

bob_p${guid}s_123abc



回答3:


You can use the standard string .format() method. Here is a link to the docs with the relevant info. You might find the following quote from the page particularly useful.

"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'.

Here is your code modified based on using the .format() method.

    # 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


来源:https://stackoverflow.com/questions/46914923/replacing-a-value-in-string-with-a-value-in-a-dictionary-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!