Replacing A Value In String With A Value In A Dictionary In 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${
Solution 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' }
Solution 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
Solution 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}" # Referencesfirst 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 offirst 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. passprint s
Post a Comment for "Replacing A Value In String With A Value In A Dictionary In Python"