我试图替换多行字符串中的一些值。为此,我执行以下步骤:
虽然它似乎有道理(对我来说)出于某种原因,它不工作。MWE附在下面:
customString = r'''%- Hello!
%- Axis limits
xmin= {xmin}, xmax= {xmax},
ymin= {ymin}, ymax= {ymax},
%- Axis labels
xlabel={xlabel},
ylabel={ylabel},
'''
tikzOptions = {'xmin': 0,
'xmax': 7.5,
'ymin': -100,
'ymax': -40,
'xlabel': '{Time (ns)}',
'ylabel': '{Amplitude (dB)}',}
for key in tikzOptions.keys():
searchKey = '{' + key + '}' # Defined key on dictionary tikzOptions
value = str(tikzOptions[key]) # Desire value for plotting
customString.replace(searchKey,value)
print(customString)
此代码的结果应为:
%- Hello!
%- Axis limits
xmin= 0, xmax= 7.5,
ymin= -100, ymax= -40,
%- Axis labels
xlabel=Time(ns),
ylabel=Amplitude (dB),
但是我得到的输出与我定义的字符串完全相同,customString。你能帮我吗
错误在这里:
Python中的字符串是不可变的,因此
.replace
返回一个新字符串。您将要执行以下操作:但是,由于您的格式也与
str.format
的格式相匹配,因此您只需执行以下操作即可一次完成
相关问题 更多 >
编程相关推荐