Replace()不适用于多行字符串和花括号

2024-10-08 19:24:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图替换多行字符串中的一些值。为此,我执行以下步骤:

  1. 我定义了一个原始字符串,在该字符串中,我稍后要自定义的值用花括号括起来
  2. 我使用自定义选项创建字典
  3. 我查看字典的键,并使用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。你能帮我吗


Tags: key字符串字典定义valuereplacexminymax
1条回答
网友
1楼 · 发布于 2024-10-08 19:24:11

错误在这里:

customString.replace(searchKey,value)

Python中的字符串是不可变的,因此.replace返回一个新字符串。您将要执行以下操作:

customString = customString.replace(searchKey,value)

但是,由于您的格式也与str.format的格式相匹配,因此您只需执行以下操作即可

result = customString.format(**tikzOptions)

一次完成

相关问题 更多 >

    热门问题