这是我的密码:
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'"updated2:
这是字符串:
'''
{
'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
},
}
......
}
}
'''发布于 2011-03-18 10:20:08
试一试
def b(a, d):
return a.format(**d)这适用于Python2.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是您的字符串。
https://stackoverflow.com/questions/5350566
复制相似问题