python html 中插入字符串

想把python变量转换成字符串插入到html代码中, 用 %s 的方式,尝试了不习惯,是需要把html的一些符号全转译吗

HighChart = '''

    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://code.highcharts.com/stock/highstock.js"></script>
    <script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
    <script src="https://code.highcharts.com/highcharts-more.js"></script>
    
    <div id="container" style="height: 400px; min-width: 310px"></div>

    <script>
        $(function(){
            Highcharts.setOptions({"global": {}, "lang": {}});
            var option = {
                
                "chart": {
                    "renderTo": "container"
                }, 
                "colors": {}, 
                "credits": {
                    "enabled": false
                }, 
                "exporting": {}, 
                "labels": {}, 
                "legend": {}, 
                "loading": {}, 
                "navigation": {}, 
                "navigator": {}, 
                "plotOptions": {
                    "series": {
                        "compare": "percent"
                    }
                }, 
                "rangeSelector": {
                    "selected": 4
                }, 
                "scrollbar": {}, 
                "series": {}, 
                "subtitle": {}, 
                "title": {"text": "A New Highchart"}, 
                "tooltip": {
                    "pointFormat": "<span style=\"color:{series.color}\">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>", "valueDecimals": 2
                }, 
                "xAxis": {}, 
                "yAxis": {
                    "labels": {
                        "formatter": function () {
                            return (this.value > 0 ? ' + ' : '') + this.value + '%';
                        }
                    },
                    "plotLines": [{"value": 0, "width": 2, "color": "silver"}]
                }
            };

            var chart = new Highcharts.StockChart(option);

            var data = "%s";
            var dataLen = data.length;
            for (var ix = 0; ix < dataLen; ix++) {
                chart.addSeries(data[ix]);
            }
        
    });
    </script>

'''
HighChart % 'daddada'
ValueError: unsupported format character ')' (0x29) at index 1480

有什么好的办法?

阅读 4.2k
3 个回答
  1. 正如 @Havaii 提到的,应该使用 jinja
  2. 如果是不愿意使用 jinja, 建议使用 "{username}-{userid}".format(username='coder',userid=1) , 不建议使用 % 和 {0} .

用"{0}".format('123')

当然是用Jinja模板引擎了,9102年了怎么会有人想着把整个html放在字符串里啊!

如果你没听说过什么是模板引擎,可以看看廖大的教程

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题