【发布时间】:2021-05-10 02:58:27
【问题描述】:
我正在尝试替换多行字符串中的一些值。为此,我执行以下步骤:
- 我定义了一个原始字符串,其中我想稍后自定义的值用大括号括起来。
- 我使用自定义选项创建字典。
- 我查看字典的键并使用 replace() 将它们替换为对应的值。
尽管出于某种原因它似乎是有道理的(对我来说)它不起作用。 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 完全相同。你能帮帮我吗?
【问题讨论】:
-
customString = customString.replace(searchKey,value) -
你为什么不用
customString.format? -
@FranciscoCouzoI 我对 python 很陌生,我对操作字符串不太了解
-
您替换了字符,但随后忽略了结果。字符串是不可变的:您不能进行就地更改。
标签: python replace multilinestring