-1

I am trying to replace some values inside a multiline string. To do that, I do the following steps:

  1. I define a raw string in which the values that I want to customize later are enclosed by curly brackets.
  2. I create a dictionary with my customization options.
  3. I look over the keys of the dictionary and replace them by their corresponding value using replace().

Altough it seems to make sense (for me) for some reason it is not working. A MWE is attached below:

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)

The result of this code should be:

%- Hello!
%- Axis limits 
xmin= 0, xmax= 7.5,
ymin= -100, ymax= -40,
%- Axis labels
xlabel=Time(ns),
ylabel=Amplitude (dB),

But the output that I get is exactly the same string that I defined, customString. Could you help me?

Jes
  • 130
  • 4

1 Answers1

2

The error is here:

customString.replace(searchKey,value)

Strings in Python are immutable, so .replace returns a new string. You'd want to do:

customString = customString.replace(searchKey,value)

However, since your format also matches that of str.format, you can simply do

result = customString.format(**tikzOptions)

and be done in one shot.

orlp
  • 112,504
  • 36
  • 218
  • 315
  • I actually had other curly brackets that had nothing to do with the dictionary parameters in my "real" string, which I did not inclue in the MWE. For future people, in this case you want to use the solution proposed by Olvin Roght and Prune, otherwise you will get an error – Jes Feb 05 '21 at 18:55
  • @Jes You can escape curly brackets when using `.format` by doubling them. E.g. `"{{hello}} {x}".format(x="world")` becomes `"{hello} world"`. – orlp Feb 05 '21 at 18:57