0

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
            },
        }
       ......
    }
}
'''
2
  • 3
    What are you trying to achieve? Your second example is very confusing. Commented Mar 18, 2011 at 10:41
  • i want to map many different Variable into a dict , and create many dict like this . Commented Mar 18, 2011 at 11:04

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

did you have other way to do this , because the string is very big , if i change {} to {{}} , that is a hard work to me . look the updated2 .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.