【问题标题】:Remove unicode characters from mysql query flask python从mysql查询烧瓶python中删除unicode字符
【发布时间】:2015-12-28 23:05:27
【问题描述】:

我浏览了许多链接,但没有得到解决方案。我在游标中有 sql 查询的结果。它们是 int、strings 等。我试图通过在 rendertemplate 中传递它并在 html 文件中循环来直接在 html 上显示它。问题是我得到了我不想要的无用字符,例如 '' 'u' 等。我知道它们是 unicde,但我无法删除它们。我已经尝试了很多方法来删除它们,但我的尝试都是徒劳的。附上我的代码。

query= ("""select Forrent.Property_id, Societyname  from ForRent,property where Type = 'Residential'; """)
   cursor.execute(query)
   cnx.commit()
   #rentable rsidential
   print "rentable resdential called"
   result =cursor

   return render_template('ViewPropertyfromMain.html', result = result)

这是我的 html 文件。我只想在 id 标题下显示结果 id,在其列标题下显示社团名称。

                <table border="1" style="width:auto">
                    <tr>
                    <th style= "font-size:35"> Property_id</th>
                    <th style= "font-size:35"> Society</th>

                  </tr>

                        {% for row in result %}
                            <tr>
                                <td style= "font-size:35">{{ row }} </td>

                            </tr>
                        {% endfor %}

                </table>

【问题讨论】:

  • 这是因为您正在打印整行,这将是 Unicode 的列表/字典 - Python 将使用 litterals 显示表示
  • 您在表格中看到\u1234 吗?还是仅在SELECTing 之后?也就是说,你是如何插入 Unicode 字符的?
  • 顺便说一句,SQL 查询看起来也很可疑,您真的是要将ForRent 中的所有行与property 中的所有行进行交叉连接吗?我怀疑你的意思是FROM ForRent JOIN property ON property.id=ForRent.Property_id

标签: python html mysql unicode flask


【解决方案1】:
                  {% for row in result %}
                        <tr>
                            {% for val in row %}
                                <td style= "font-size:35">{{ val }} </td>
                            {% endfor %}

                        </tr>
                    {% endfor %}

您必须遍历该行...事实上它的 unicode 或 str 真的无关紧要:P

【讨论】:

  • 男人!有效!非常感谢。
【解决方案2】:

您必须在传递给模板的每个字符串上调用str。例如,如果结果是可迭代的,你可以尝试这样的事情

cleaned_result = [str(i) for i in result]

【讨论】:

  • 虽然这将尝试转换为 ascii 位 str (很可能有 UnicodeDecode 错误)......我怀疑这正是 OP 真正想要的......我可能是错的...... .
  • 在 Python 2.x 中,在第一个非 ASCII 字符处中断
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 2017-09-18
  • 1970-01-01
  • 2021-08-28
  • 2014-11-14
  • 2014-07-20
  • 2015-04-23
相关资源
最近更新 更多