search

PYTHON blog records

Jun 23, 2017 pm 02:47 PM
pythonblogRecord

1. Python#UnicodeString

Characters There is also an encoding issue with strings.

#Because computers can only process numbers, if you want to process text, you must first convert the text into numbers before processing. The earliest computers were designed using 8 bits (bit) as a byte (byte) , so the largest integer that can be represented by one byte is 255 (binary 11111111=decimal 255 ), 0 - 255 is used to represent uppercase and lowercase English letters, numbers and some symbols. This encoding table is called ASCII encoding, for example, the encoding for uppercase letters A is 65, and for lowercase letters z The encoding of is 122.

#If you want to represent Chinese, obviously one byte is not enough, at least two bytes are needed. And it cannot conflict with the ASCII encoding. Therefore, China has formulated the GB2312 encoding to encode Chinese characters.

Similarly, other languages ​​such as Japanese and Korean also have this problem. In order to unify the encoding of all text, Unicode came into being. UnicodeUnify all languages ​​into one set of encodings, so that there will no longer be garbled code problems.

UnicodeUsually two bytes are used to represent a character. The original English encoding changed from a single byte To become double-byte, just fill in the high byte as 0.

Because the birth of Python is faster than Unicode The standard was released even earlier, so the earliest Python only supports ASCII encoding, ordinary strings'ABC' is encoded internally in Python#ASCII.

Python later added support for Unicode, and the string represented by Unicode is u'...' represents, for example:

print u'中文'

UnicodeString Except for the extra u , it is no different from an ordinary string. The escape characters and multi-line representation are still valid:


print u'中文\n日文\n韩文'

Multiple lines:

u'''第一行
第二行'''

raw+Multiple lines:

ur'''Python的Unicode字符串支持"中文",
"日文",
"韩文"等多种语言'''

If the Chinese string is in UnicodeDecodeError is encountered in the Python environment. This is because there is a problem with the format of the .py file. You can add a comment

# -*- coding: utf-8 -*-

on the first line to tell the Python interpreter to use UTF-8Encoding reads source code. Then use Notepad++ to save as ... and select the UTF-8 format save.

2. PythonIntegers and floating-point numbers

Python supports direct mixed arithmetic operations on integers and floating-point numbers. The operation rules are completely consistent with the four arithmetic operations rules in mathematics.

Basic operations:

1 + 2 + 3   # ==> 6
4 * 5 - 6   # ==> 14
7.5 / 8 + 2.1   # ==> 3.0375
(1 + 2) * 3    # ==> 9
(2.2 + 3.3) / (1.5 * (9 - 0.3))    # ==> 0.42145593869731807


Using parentheses can increase the priority, which is exactly the same as mathematical operations. Note that only parentheses can be used, but parentheses can be nested in many levels: ## The difference between

# and mathematical operations is that the result of Python's integer operation is still an integer, and the result of floating-point operation is still a floating-point number:

1 + 2    # ==> 整数 3
1.0 + 2.0    # ==> 浮点

But the result of the mixed operation of integers and floating point numbers becomes floating point numbers:

1 + 2.0    # ==> 浮点数 3.0

为什么要区分整数运算和浮点数运算呢?这是因为整数运算的结果永远是精确的,而浮点数运算的结果不一定精确,因为计算机内存再大,也无法精确表示出无限循环小数,比如 0.1 换成二进制表示就是无限循环小数。

 

那整数的除法运算遇到除不尽的时候,结果难道不是浮点数吗?

11 / 4    # ==> 2


令很多初学者惊讶的是,Python的整数除法,即使除不尽,结果仍然是整数,余数直接被扔掉。不过,Python提供了一个求余的运算 % 可以计算余数:

11 % 4    # ==> 3

如果我们要计算 11 / 4 的精确结果,按照“整数和浮点数混合运算的结果是浮点数”的法则,把两个数中的一个变成浮点数再运算就没问题了:

11.0 / 4    # ==> 2.75

三、Python中布尔类型

 

#与运算
True and True   # ==> True
True and False   # ==> False
False and True   # ==> False
False and False   # ==> False

#或运算
True or True   # ==> True
True or False   # ==> True
False or True   # ==> True
False or False   # ==> False

#非运算
not True   # ==> False
not False   # ==> True

a = True
print a and 'a=T' or 'a=F'
#计算结果不是布尔类型,而是字符串 'a=T',这是为什么呢?

#因为Python把0、空字符串''和None看成 False,其他数值和非空字符串都看成 True,所以:

True and 'a=T' #计算结果是 'a=T'
#继续计算 'a=T' or 'a=F' 计算结果还是 'a=T'

要解释上述结果,又涉及到 and or 运算的一条重要法则:短路计算。

1. 在计算 a and b 时,如果 a False,则根据与运算法则,整个结果必定为 False,因此返回 a;如果 a True,则整个计算结果必定取决与 b,因此返回 b

 

2. 在计算 a or b 时,如果 a True,则根据或运算法则,整个计算结果必定为 True,因此返回 a;如果 a False,则整个计算结果必定取决于 b,因此返回 b

 

所以Python解释器在做布尔运算时,只要能提前确定计算结果,它就不会往后算了,直接返回结果。

 

 

 

 

 

 

四、Python创建list

Python内置的一种数据类型是列表:listlist是一种有序的集合,可以随时添加和删除其中的元素。

 

比如,列出班里所有同学的名字,就可以用一个list表示:

>>> ['Michael', 'Bob', 'Tracy']
['Michael', 'Bob', 'Tracy']

list是数学意义上的有序集合,也就是说,list中的元素是按照顺序排列的。

 

构造list非常简单,按照上面的代码,直接用 [ ] list的所有元素都括起来,就是一个list对象。通常,我们会把list赋值给一个变量,这样,就可以通过变量来引用list

classmates = ['Michael', 'Bob', 'Tracy']
classmates # 打印classmates变量的内容
>>>['Michael', 'Bob', 'Tracy']

由于Python是动态语言,所以list中包含的元素并不要求都必须是同一种数据类型,我们完全可以在list中包含各种数据:

L = ['Michael', 100, True]

一个元素也没有的list,就是空list

empty_list = []
#打印成绩表
L = ['adam', 95.5,'lisa', 85,'bart', 59]
print L

 

五、Python按照索引访问list


由于list是一个有序集合,所以,我们可以用一个list按分数从高到低表示出班里的3个同学:

L = ['Adam', 'Lisa', 'Bart']

那我们如何从list中获取指定第 N 名的同学呢?方法是通过索引来获取list中的指定元素。

 

需要特别注意的是,索引从 0 开始,也就是说,第一个元素的索引是0,第二个元素的索引是1,以此类推。

 

因此,要打印第一名同学的名字,用 L[0]:

但使用索引时,千万注意不要越界,所以没有L[3]

六、Python之倒序访问list

L = ['Adam', 'Lisa', 'Bart']
print L[-1]
>>>Bart

 


七、Pythonlist添加新元素

L = ['Adam', 'Lisa', 'Bart']

 

把新同学Paul添加到现有的 list

7.1append()

第一个办法是用 list append() 方法,把新同学追加到 list 的末尾:

L = ['Adam', 'Lisa', 'Bart']
L.append('Paul')
print L
>>> ['Adam', 'Lisa', 'Bart', 'Paul']

append()总是把新的元素添加到 list 的尾部。

 

7.2insert()

  listinsert()方法,它接受两个参数,第一个参数是索引号,第二个参数是待添加的新元素:

L = ['Adam', 'Lisa', 'Bart']
L.insert(0, 'Paul')
print L
>>>['Paul', 'Adam', 'Lisa', 'Bart']

L.insert(0, 'Paul') 的意思是,'Paul'将被添加到索引为 0 的位置上(也就是第一个),而原来索引为 0 Adam同学,以及后面的所有同学,都自动向后移动一位。

 

八、Python从list删除元素

 L = ['Adam', 'Lisa', 'Bart', 'Paul']
L.pop()
>>>'Paul'
 print L
>>>['Adam', 'Lisa', 'Bart']

pop()默认删除最后一个,当让也可以指定

L = ['Adam', 'Lisa', 'Paul', 'Bart']
L.pop(2)
>>>'Paul'
print L
>>> ['Adam', 'Lisa', 'Bart']


九、PythonList中替换元素

L = ['Adam', 'Lisa', 'Paul', 'Bart']
L[2] = 'Paul' #或者 L[-1] = 'Paul'
print L
>>> L = ['Adam', 'Lisa', 'Paul']

十、Python之创建tuple

tuple是另一种有序的列表,中文翻译为“ 元组 ”。tuple list 非常类似,但是,tuple一旦创建完毕,就不能修改了。

 

同样是表示班里同学的名称,用tuple表示如下:

t = ('Adam', 'Lisa', 'Bart')

  

创建tuple和创建list唯一不同之处是用( )替代了[ ]

 

现在,这个 t 就不能改变了,tuple没有 append()方法,也没有insert()pop()方法。所以,新同学没法直接往 tuple 中添加,老同学想退出 tuple 也不行。

 

获取 tuple 元素的方式和 list 是一模一样的,我们可以正常使用 t[0]t[-1]等索引方式访问元素,但是不能赋值成别的元素

 

十一、Python之创建单元素tuple

tuplelist一样,可以包含 0 个、1个和任意多个元素。

 

包含多个元素的 tuple,前面我们已经创建过了。

 

包含 0 个元素的 tuple,也就是空tuple,直接用 ()表示:

t = ()
print t
>>>()

  

 t = (1)
print t
>>> 1
#???这是为什么,因为()既可以表示tuple,又可以作为括号表示运算时的优先级,结果 (1) 被Python解释器计算出结果 1,导致我们得到的不是tuple,而是整数 1。

  

正是因为用()定义单元素的tuple有歧义,所以 Python 规定,单元素 tuple 要多加一个逗号“,”,这样就避免了歧义:

t = (1,)
print t
>>>(1,)

Python在打印单元素tuple时,也自动添加了一个“,”,为了更明确地告诉你这是一个tuple

 

多元素 tuple 加不加这个额外的“,”效果是一样的。

 

 


十二、Python之“可变”的tuple

 

t = ('a', 'b', ['A', 'B'])
#t = ('a', 'b', ('A', 'B'))的话就是不可变的

注意到 t 3 个元素:'a''b'和一个list['A', 'B']list作为一个整体是tuple的第3个元素。list对象可以通过 t[2] 拿到:

 L = t[2]
L[0] = 'X'
L[1] = 'Y'
print t
>>>('a', 'b', ['X', 'Y'])

 

The above is the detailed content of PYTHON blog records. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

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),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.