如何使用Python映射字符串

0 投票
1 回答
922 浏览
提问于 2025-04-16 13:57

这是我的代码:

a= ''' ddwqqf{x}'''
def b():
    ...

c=b(a,{'x':'!!!!!'})
print c

我想得到 ddwqqf!!!!!

那么我该如何创建 b 函数呢,

谢谢

更新:

但是我该如何做这个事情:

a= ''' ddwqqf{x},{'a':'aaaa'}'''

c = a.format(x="!!!!!")

d= open('a.txt','a')
d.write(c)

它显示错误:

Traceback (most recent call last):
  File "d.py", line 8, in <module>
    c = a.format(x="!!!!!")
KeyError: "'a'"

更新2:

这是字符串:

'''
{
    '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
            },
        }
       ......
    }
}
'''

1 个回答

3

试试这个

def b(a, d):
    return a.format(**d)

这个在Python 2.6或更高版本中可以用。当然,你不需要为这个定义一个函数:

a = " ddwqqf{x}"
c = a.format(x="!!!!!")

这样就足够了。

编辑关于你的更新:

a = " ddwqqf{x},{{'a':'aaaa'}}"

为了避免对第二对大括号的替换。

另一个编辑:我其实不太清楚你的字符串是从哪里来的,以及这一切的背景是什么。一个解决方案可能是

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)

这里的s就是你的字符串。

撰写回答