how to map the string using python
this is my code :
a= ''' ddwqqf{x}'''
def b():
...
c=b(a,{'x':'!!!!!'})
print c
i want to get ddwqqf!!!!!
,
so how to create the b
function ,
thanks
updated:
but how to do this thing :
a= ''' ddwqqf{x},{'a':'aaaa'}'''
c = a.format(x="!!!!!")
d= open('a.txt','a')
d.write(c)
it show error :
Traceback (most recent call last):
File "d.py", line 8, in <module>
c = a.format(x="!!!!!")
KeyError: "'a'"
updated2:
this is the string:
'''
{
'skill': {x_1},
'power': {x_2},
'magic': {x_3},
'level': {x_4},
'weapon': {
0 : {
'item': {
'weight': 40,
'target': 1,
'defence': 100,
'name': u'\uff75\uff70\uff78\uff7f\uff70\uff84',
'attack': 100,
'type': 1
},
},
1 : {
'item': {
'weight': 40,
'target': 1,
'defence': 100,
'name': u'\uff75\uff70\uff78\uff7f\uff70\uff84',
'attack': 100,
'type': 1
},
},
2 : {
'item': {
'weight': 40,
'target': 1,
'defence': 100,开发者_运维百科
'name': u'\uff75\uff70\uff78\uff7f\uff70\uff84',
'attack': 100,
'type': 1
},
}
......
}
}
'''
Try
def b(a, d):
return a.format(**d)
This works in Python 2.6 or above. Of course you would not need to define a function for this:
a = " ddwqqf{x}"
c = a.format(x="!!!!!")
will be enough.
Edit regarding your update:
a = " ddwqqf{x},{{'a':'aaaa'}}"
to avoid substitutions for the second pair of braces.
Another Edit: I don't really know where your string comes from and what's the context of all this. One solution might be
import re
d = {"x_1": "1", "x_2": "2", "x_3": "3", "x_4": "4"}
re.sub(r"\{([a-z_0-9]+)\}", lambda m: d[m.group(1)], s)
where s
is your string.
精彩评论