[英]python - replace string entry with a dictionary entry
I have a string like 'MATERIAL 4 {clad-den} {clad-temp} 2'
, and I want to replace entries like {clad-den}
, {clad-temp}
(in figure brackets) with corresponding values from a dictionary, which have the same key, as enclosed in brackets - like data['clad-den']
to receive a string like: 'MATERIAL 4 6.55 578.0 2'
. 我有一个类似
'MATERIAL 4 {clad-den} {clad-temp} 2'
的字符串,我想用字典中的相应值替换诸如{clad-den}
, {clad-temp}
类的条目,具有相同的密钥,如括在方括号内的data['clad-den']
以接收类似'MATERIAL 4 6.55 578.0 2'
的字符串。 How can I do that? 我怎样才能做到这一点?
I have some thoughts directed at re.sub
. 我对
re.sub
有一些想法。 Something like: re.sub(('{\\S+}'),data[('\\S+')],string)
, but I don't know how to make it use the same key as it's replacing each time. 有点像:
re.sub(('{\\S+}'),data[('\\S+')],string)
,但是我不知道如何使它使用与每次替换相同的键。
You can use str.format()
out of the box for this: 您可以立即使用
str.format()
:
'MATERIAL 4 {clad-den} {clad-temp} 2'.format(**data)
This will look up clad-den
and clad-temp
as keys in the data
dictionary: 这将查找
clad-den
和clad-temp
作为data
字典中的键:
>>> data = {'clad-den': 6.55, 'clad-temp': 578.0}
>>> 'MATERIAL 4 {clad-den} {clad-temp} 2'.format(**data)
'MATERIAL 4 6.55 578.0 2'
You can do it with re.sub()
too, using a function for the replacement parameter: 您也可以使用
re.sub()
来实现它,对替换参数使用函数:
re.sub(r'{([^{}]+)}', lambda m: str(data[m.group(1)]), template_text)
but this doesn't offer the same flexibility and power that string formatting can offer. 但这不能提供字符串格式化所提供的灵活性和功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.