编码 python

2024-09-26 17:49:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python中连接一些字符串(波斯语字符串):

            for t in lstres:
            with conn:
                c = conn.cursor()   
                q="SELECT fa FROM words WHERE en ='"+t+"'"
                c.execute(q)
                lst=c.fetchall()

                if lst:
                    W.append(lst)
                else:
                    W.append(t)

        cnum=1
        for can in W:
            cnum=cnum*len(W)

        candida=Set()

        for ii in range(1,min(20,cnum)):
            candid=""
            for w in W:
                candid+=str(" "+random.choice (w)[0]).encode('utf-8')
            candida.add(candid)

但上面写着:

^{pr2}$

有什么问题吗?在


Tags: 字符串infromforwithconnselectcursor
3条回答

问题在于:

for ii in range(1,min(20,cnum)):
   candid=""
   for w in W:
       candid+=str(" "+random.choice (w)[0]).encode('utf-8')
    candida.add(candid)

应该是的

^{pr2}$

但它不是惯用的python

你应该这么做

^{3}$

此外,您的脚本中还有一个潜在的sql注入

q="SELECT fa FROM words WHERE en ='"+t+"'"
c.execute(q)

你应该这么做

q="SELECT fa FROM words WHERE en =?"
c.execute(q, (t,))

(t,)是一个只有一个元素的元组

您需要将字符串声明为Unicode:

u'Your string here éàèç×...'

Python正试图从unicode字符串到ASCII编码字符串进行隐式类型转换。从您发布的内容中很难判断这是在哪里发生的,但是最好确保您始终使用unicode。为此,您需要在所有字符串前面添加一个u,例如:u"A unicode string",并始终使用unicode(),而不是{}。在

Unicode常常被英语程序员和教程忽视,因为在英语中,您可以通过使用ASCII编码字符来逃避惩罚。不幸的是,世界其他地方也因此而受苦,因为大多数语言使用ASCII不支持的字符。查看Python Unicode HOWTO可以得到一些关于Unicode良好编程实践的指导。在

{a2}我发现这篇文章也很有用。在

相关问题 更多 >

    热门问题