簡體   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