0

I have generated a string as follows,

Code:

    html_chart = chart.to_html()
    # These offsets will be the same for any chart
    start = html_chart.index('vegaEmbed') - 10
    end = html_chart.index('vegaEmbed);') + 11
    print(html_chart[start:end])

output:

(function(vegaEmbed) {
      var spec = {"config": {"view": {"continuousWidth": 400, "continuousHeight": 300}}, "data": {"url": "https://cdn.jsdelivr.net/npm/vega-datasets@v1.29.0/data/cars.json"}, "mark": "circle", "encoding": {"x": {"field": "Horsepower", "scale": {"nice": false}, "type": "quantitative"}, "y": {"field": "Miles_per_Gallon", "type": "quantitative"}}, "$schema": "https://vega.github.io/schema/vega-lite/v5.2.0.json"};
      var embedOpt = {"mode": "vega-lite"};

      function showError(el, error){
          el.innerHTML = ('<div class="error" style="color:red;">'
                          + '<p>JavaScript Error: ' + error.message + '</p>'
                          + "<p>This usually means there's a typo in your chart specification. "
                          + "See the javascript console for the full traceback.</p>"
                          + '</div>');
          throw error;
      }
      const el = document.getElementById('vis');
      vegaEmbed("#vis", spec, embedOpt)
        .catch(error => showError(el, error));
    })(vegaEmbed);

Now I need to replace the vis keyword with myID. I have used following code, but I could not replace the word. Are there any different syntax to use?

html_chart.replace('vis', 'myID')
Shehan
  • 417
  • 2
  • 11
  • 2
    Strings are immutable, so `str.replace()` returns a _modified copy_ of the string instead of mutating the original. You probably want to do `html_chart = html_chart[:start] + html_chart[start:end].replace('vis', 'myID') + html_chart[end:]` – Green Cloak Guy Jun 06 '22 at 04:27
  • @GreenCloakGuy Great. It worked.. SInce you have not put it as an answer, I cannot make accepted. Sorry for that. I upvoted – Shehan Jun 06 '22 at 04:32
  • Surely just `html_chart = html_chart.replace('vis', 'myID')`? – Nick Jun 06 '22 at 04:35

0 Answers0