Problems encountered in playing Python 123 and solutions

Recently, I have been playing Python frequently, and I will summarize some of the problems encountered here, which will be continuously updated.

Question 1: The python 2.7 version solves TypeError: 'encoding' is an invalid keyword argument for this function.
When using Python 2.7 to open some files, the above-mentioned problems often occur, such as

data_file = open("F:\\MyPro\\data.yaml", "r", encoding='utf-8')

Error when running: TypeError: 'encoding' is an invalid keyword argument for this function. But running in Py3 does not encounter such a problem .
Solution: After searching on the Internet, change it to the following so you can get it

import io
data_file = io.open("F:\\MyPro\\data.yaml", "r", encoding='utf-8')

The reason is not particularly clear, maybe it is related to the different API regulations of Py2 and Py3.

Question 2: When python reads the file, it prompts "UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 205: illegal multibyte sequence". The
same thing is the encoding problem encountered when reading the file.
Solution:

FILE_OBJECT= open('order.log','r', encoding='UTF-8')

You only need to add the corresponding encoding parameter and it is OK. For encoding problems in Python, it is sometimes very troublesome. However, such problems can generally be found under Baidu.

Question 3: Not enough arguments for format string
When executing SQL query statements in Python, such an error occurs, eg
sql='select * from Teacher where Tname like \'%%'+ keyword +'%%\''. Only later did I know that this kind of problem occurs, mainly because the string contains the % sign. Python thinks it is a transfer character, but what we actually need is %. At this time, we can use %% to represent %.

Question 4: The output information is an escape code

# ((u'01', u'\u5f20\u4e09'), (u'04', u'\u5f20\u4e09\u4e30')) # (u'01', u'\u5f20\u4e09')

This situation only occurs in Py2, and does not occur in Py3.
Solution: Convert the output escape code to the corresponding Chinese by the following eval method.

 print(eval("u"+"\'"+exmple[1]+"\'"))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325807825&siteId=291194637