Landlord, this problem is generally due to the need for the database encoding format, you first confirm that your database is what encoding, and then in the storage before the corresponding conversion can be, this problem I encountered many times, I believe that we are encountering the same problem.
Let me give you a reference, please.
For example, I get a str from a UTF-8 encoded file and want to save it to txt in Windows, I should convert the following before I deposit it:
msg_gbk=msg.decode(‘UTF-8‘).encode(‘GBK‘)
这个时候把msg_gbk存进txt里面,就不会产生乱码了。
Today is the MySQL Chinese question.
1. First set the database's table encoding to GBK.
2. python file, encoding set to GBK
Import sysreload (SYS) sys.setdefaultencoding (' GBK ')
3. Then add
str = str.encode (' raw_unicode_escape ') str = str.decode (' unicode_escape ') print str# should be able to output a readable Chinese and then deposit the library on it.
The representation of a string inside Python is Unicode encoding, so in encoding conversion, it is usually necessary to use Unicode as the intermediate encoding, that is, decoding the other encoded string (decode) into Unicode first. From Unicode encoding (encode) to another encoding.
The role of Decode is to convert other encoded strings into Unicode encodings, such as Str1.decode (' gb2312 '), to convert gb2312 encoded string str1 into Unicode encoding.
The role of encode is to convert Unicode encoding into other encoded strings, such as Str2.encode (' gb2312 '), to convert Unicode encoded string str2 to gb2312 encoding.
Therefore, the transcoding must first understand, the string str is what encoding, and then decode into Unicode, and then encode into other encodings
The default encoding of the string in the code is consistent with the encoding of the code file itself .
such as: s= ' Chinese '
If it is in a UTF8 file, the string is UTF8 encoded, and if it is in a gb2312 file, it is encoded as gb2312. In this case, to encode the conversion, you need to first convert it to Unicode encoding using the Decode method, and then use the Encode method to convert it to another encoding. Typically, you create a code file by using the system default encoding when you do not specify a specific encoding method.
If the string is defined like this: S=u ' Chinese '
The encoding of the string is specified as Unicode, which is the internal encoding of Python, regardless of the encoding of the code file itself. Therefore, for this case to do the encoding conversion, only need to directly use the Encode method to convert it to the specified encoding.
If a string is already Unicode, then decoding will be an error, so it is common to determine whether it is encoded as Unicode:
Isinstance (S, Unicode) # is used to determine if Unicode
Encode with a non-Unicode encoded form of STR will error
Database Chinese garbled