【问题标题】:Replace() not working on multiline string and curly bracketsReplace() 不适用于多行字符串和大括号
【发布时间】:2021-05-10 02:58:27
【问题描述】:

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

  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 完全相同。你能帮帮我吗?

【问题讨论】:

  • customString = customString.replace(searchKey,value)
  • 你为什么不用customString.format
  • @FranciscoCouzoI 我对 python 很陌生,我对操作字符串不太了解
  • 您替换了字符,但随后忽略了结果。字符串是不可变的:您不能进行就地更改。

标签: python replace multilinestring


【解决方案1】:

错误在这里:

customString.replace(searchKey,value)

Python 中的字符串是不可变的,因此.replace 返回一个新字符串。你想做的事:

customString = customString.replace(searchKey,value)

但是,由于您的格式也与 str.format 匹配,您可以简单地做

result = customString.format(**tikzOptions)

一口气完成。

【讨论】:

  • 我实际上还有其他大括号与我的“真实”字符串中的字典参数无关,我没有将其包含在 MWE 中。对于未来的人,这种情况下你要使用 Olvin Roght 和 Prune 提出的解决方案,否则会报错
  • @Jes 在使用.format 时,您可以通过将大括号加倍来转义大括号。例如。 "{{hello}} {x}".format(x="world") 变为 "{hello} world"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-30
  • 1970-01-01
相关资源
最近更新 更多