简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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