A good article about STR and UNICODE
Organize the content related to python coding
Note: The following discussion is for the Python2.x version, Py3k is to be tried
Start
When using python to process Chinese, read files or messages, http parameters, etc.
As soon as I run it, garbled characters are found (string processing, reading Write a file, print)
Then, what most people do is to call encode/decode for debugging, without clearly thinking about why garbled characters appear
So the most common errors during debugging
Error 1
Traceback (most recent call last): File "
Error 2
##Traceback (most recent call last): File "
First of all
You must have a general concept, understand the character set, character encodingASCII | Unicode | UTF-8 | etc. Character encoding notes: ASCII, Unicode and UTF-8Taobao Search Technology Blog-Chinese Encoding Talkstr and unicode
both str and unicode It is a subclass of basestringSo there is a method to determine whether it is a stringdef is_str(s): return isinstance(s, basestring)
str -> decode('the_coding_of_str') -> unicode unicode -> ; encode('the_coding_you_want') -> str
Difference
str is a byte string, which is encoded by unicode Declaration method consisting of bytess = 'Chinese' s = u'中文'.encode('utf-8') >>> type( 'Chinese')
>>> u'中文'.encode('utf-8') '\xe4\xb8\xad\xe6\x96\x87' >>> len(u'中文'.encode('utf-8')) 6
Declaration method
s = u'Chinese ' s = '中文'.decode('utf-8') s = unicode('中文', 'utf-8') >>> type(u'中文')
>>> u'中文' u'\ u4e2d\u6587' >>> len(u'中文') 2
Understand that str is what needs to be processed Or unicode, use the right processing method (str.decode/unicode.encode)
The following is the method to determine whether it is unicode/str
>>> isinstance(u'中文', unicode) True >>> isinstance('中文', unicode) False >>> isinstance('中文', str) True >>> isinstance(u'中文', str) False
Simple principle: do not use encode for str and do not use decode for unicode (in fact, str can be encoded, see the end for details. To ensure simplicity, it is not recommended)
>>> '中文'.encode('utf-8') Traceback (most recent call last): File "
Different encoding conversions, use unicode as the intermediate encoding
File processing, IDE and console
The processing process can be used like this. Think of python as a pool, an entrance, and an exit.
At the entrance, all are converted to unicode, and all in the pool are processed with unicode. At the exit, they are converted to the target encoding. (Of course, there are exceptions, and specific encoding needs to be used in the processing logic)
Read the file, external input encoding, decode into unicode, process (internal encoding, unified unicode), encode into the required target encoding, write to the target output (file or console)
IDE and control The reason for the error is that when printing, the encoding is inconsistent with the IDE's own encoding.
Convert the encoding to a consistent one during output and the output will be normal.
##>>> print u '中文'.encode('gbk') ???? >>> print u'中文'.encode('utf-8') 中文
It is recommended that
standardize the coding
unify the coding to prevent garbled codes caused by a certain link
Environment coding, IDE/text editor, file coding, database data table coding
Ensure code source file coding
This is very important
The default encoding of py files is ASCII. In the source code file, if non-ASCII characters are used, the encoding declaration document needs to be declared in the header of the file. If not declared, inputting non-ASCII will cause Errors encountered must be placed on the first or second line of the file File "XXX.py", line 3 SyntaxError: Non-ASCII character '\xd6' in file c.py on line 3, but no encoding declared; see http://www.php.cn/ for detailsDeclaration method
# -*- coding: utf-8 -*- or #coding=utf- 8
Processing order
1. Decode early 2. Unicode everywhere 3. Encode laterstr.encode('other_coding')
In python, directly encode a certain encoding str into another encoding str
#str_A is utf-8 str_A.encode('gbk') The operation performed is str_A.decode('sys_codec').encode('gbk') Here sys_codec is the encoding of sys.getdefaultencoding() in the previous step
'Getting and setting the system default encoding' is related to str.encode here, but I rarely use it this way. Mainly because it feels complicated and uncontrollable, and it is better to input clear decode and output clear encode. Simpler (personal opinion)
chardet
File encoding detection, download
>>> import chardet >>> f = open ('test.txt','r') >>> result = chardet.detect(f.read()) >>> result {'confidence': 0.99, 'encoding': 'utf- 8'}
\uString to corresponding unicode string
The above is the collection of information on Python coding processing. We will continue to add relevant information in the future. Thank you for your support of this site!
For more Python encoding processing-str and Unicode related articles, please pay attention to the PHP Chinese website!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
