EncodeError with \xa3 (pound sign)

与世无争的帅哥 提交于 2019-12-23 01:21:11

问题


I'm trying to get some data from a web page. This webpage has stated that charset is utf-8. But there is a problem with \xa3 sign. I can't be encoded or decoded into/from 'utf-8'.

for key,value in self.__dict__.iteritems():
            if key not in self.db_attributes:
                print repr(value)
                attrs_statement+=str(key)+', '
                values_statement+=str(value)+', '

ERROR:

u'\xa3410'
Traceback (most recent call last):
  File "C:\Users\Milano\My Documents\LiClipse Workspace\Velvet_scraper\vehicle.py", line 432, in <module>
    v.prepare_insert_statement('motorhog_temp')
  File "C:\Users\Milano\My Documents\LiClipse Workspace\Velvet_scraper\vehicle.py", line 381, in prepare_insert_statement
    values_statement+=str(value)+', '
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 0: ordinal not in range(128)

What is wrong with that please?

EDIT:

Whole method:

def prepare_insert_statement(self,table):
        log('prepare_insert_statement, table: {0}'.format(table))

        attrs_statement = "("
        values_statement = "("

        for key,value in self.__dict__.iteritems():
            if key not in self.db_attributes:
                print repr(value)
                attrs_statement+=key+', '
                values_statement+=value+', '

        attrs_statement+=')'
        values_statement+=')'
        statement = """INSERT INTO TABLE {0}{1} VALUES{2}""".format(table,attrs_statement,values_statement)
        return statement

回答1:


str() implicitly encodes Unicode objects with the ASCII codec. Explicitly encode your object, or do not use str() objects and build up a Unicode string instead:

values_statement += value.encode('utf8') + ', '


来源:https://stackoverflow.com/questions/31746333/encodeerror-with-xa3-pound-sign

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!