简体   繁体   English

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

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

I have function in python that takes few strings and should join them with a bigger string that should be a 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()

When i get the code running, the file gets created and then I get error: 当我运行代码时,创建了文件,然后出现错误:

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

I have read few topics on this subject and I am worried that my error has something to do with joining function arguments with this mess of a string. 我已经读过很少的有关此主题的主题,并且我担心我的错误与将函数参数与此字符串弄乱有关。 However, the error does not say anything about me messing the format of the string, and maybe there is something with that? 但是,该错误并没有说明我弄乱了字符串的格式,也许与此有关?

The problem is Python (before version 3, according to my own tests), didn't like UTF-8 for output, so you're limited by default to use ASCII 问题是Python(根据我自己的测试,在版本3之前),不喜欢UTF-8进行输出,因此默认情况下您只能使用ASCII码

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

Here are the tests: Python 1 , Python 2 , Python 3 测试如下: Python 1Python 2Python 3

Anyway, you should be able to do something like this: 无论如何,您应该可以执行以下操作:

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

Here are the tests for print working with this fix: Python 1 , Python 2 以下是使用此修复程序进行print的测试: Python 1Python 2

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

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