繁体   English   中英

将带有变量字符串的多行保存到html文件

[英]Saving multi-line with variables string to html file

我在python中有函数,它需要几个字符串,应该将它们与应该是html文件的更大字符串连接在一起。

def manzy(product_name, product_image, product_price_new, product_price_before):
a = """  <!DOCTYPE html>
            <html>
              <head>
                <meta charset="UTF-8">
                <title>title</title>
                    <link rel="stylesheet" type="text/css" href="maincss.css">
              </head>
              <body>

                    <div class="shop-card">
                      <div class="title"> """ + product_name + """ </div>


                      <div class="desc">
                            Womans cloath
                      </div>
                      <div class="slider">
                            <figure data-color="#E24938, #A30F22 "> 
                              <img src=""" +  product_image + """/>
                            </figure>
                      </div>

                      <div class="cta">
                            <div class="price"> """ + product_price_new + """</div><br>
                            <div class="price"> """ + product_price_before + """</div>

                      </div>
                    </div>
                    <div class="bg"></div>

            </div>

              </body>
            </html> """

Html_file= open("filename","w")
Html_file.write(a)
Html_file.close()

当我运行代码时,创建了文件,然后出现错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 400: ordinal not in range(128)

我已经读过很少的有关此主题的主题,并且我担心我的错误与将函数参数与此字符串弄乱有关。 但是,该错误并没有说明我弄乱了字符串的格式,也许与此有关?

问题是Python(根据我自己的测试,在版本3之前),不喜欢UTF-8进行输出,因此默认情况下您只能使用ASCII码

a = u'\xe7'
print(a) # Throws the error on Python 1 and 2, works fine on Python 3

测试如下: Python 1Python 2Python 3

无论如何,您应该可以执行以下操作:

Html_file.write(a.encode('utf-8'))

以下是使用此修复程序进行print的测试: Python 1Python 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM