doc: update docs/python.md (#394)

* doc: 修正 Python 清单中的机翻文本

* doc: 增补注释和示例,使用例更贴合本土

* doc: 更正修正中的错误

* doc: 配合 #385 将介绍中的链接也改为中文版
This commit is contained in:
砹小翼 2023-07-12 13:42:21 +08:00 committed by GitHub
parent 0d0e92dd56
commit fb1fa4b47f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -8,46 +8,48 @@ Python 备忘单是 [Python 3](https://www.python.org/) 编程语言的单页参
### 介绍 ### 介绍
- [Python](https://www.python.org/) _(python.org)_ - [Python 官方网站](https://www.python.org/) _(python.org)_
- [Python 文档](https://docs.python.org/zh-cn/3/index.html) _(docs.python.org)_ - [Python 文档](https://docs.python.org/zh-cn/3/index.html) _(docs.python.org)_
- [Learn X in Y minutes](https://learnxinyminutes.com/docs/python/) _(learnxinyminutes.com)_ - [Y 分钟学会 Python](https://learnxinyminutes.com/docs/zh-cn/python-cn/) _(learnxinyminutes.com)_
- [Regex in python](./regex.md#python-中的正则表达式) _(jaywcjlove.github.io)_ - [Python 中的正则表达式](./regex.md#python-中的正则表达式) _(jaywcjlove.github.io)_
### Hello World ### 控制台打印
```python ```python
>>> print("Hello, World!") >>> print("Hello, World!")
Hello, World! Hello, World!
``` ```
Python 中著名的“Hello World”程序 著名的“Hello World”程序在 Python 中的实现
### 变量 ### 变量
```python ```python
age = 18 # 年龄是 int 类型 age = 18 # 年龄是 int 类型
name = "John" # name 现在是 str 类型 name = "John" # 名字现在是 str 类型
print(name) print(name)
``` ```
Python 不能在没有赋值的情况下声明变量 - Python 不能在没有赋值的情况下声明变量
- 变量可以存放不同类型的值
### 数据类型 ### 内置数据类型
<!--rehype:wrap-class=row-span-2--> <!--rehype:wrap-class=row-span-2-->
序列指一批有序的元素,集合指一批无序且不重复的元素
:-| :- | :- | :- |
:-| :- |:----------------------------------------|:-----------------|
`str` | Text | `str` | 文本/字符串(Text |
`int`, `float`, `complex` | Numeric | `int`, `float`, `complex` | 数值(Numeric |
`list`, `tuple`, `range` | Sequence | `dict` | 映射键值对Mapping |
`dict` | Mapping | `list`, `tuple`, `range` | 序列Sequence |
`set`, `frozenset` | Set | `set`, `frozenset` | 集合(Set |
`bool` | Boolean | `bool` | 布尔值/逻辑值(Boolean |
`bytes`, `bytearray`, `memoryview` | Binary | `bytes`, `bytearray`, <br> `memoryview` | 二进制数据(Binary |
查看: [Data Types](#python-数据类型) 查看: [数据类型](#python-数据类型)
### Slicing String ### 字符串切片
```python ```python
>>> msg = "Hello, World!" >>> msg = "Hello, World!"
@ -55,9 +57,9 @@ Python 不能在没有赋值的情况下声明变量
llo llo
``` ```
查看: [Strings](#python-字符串) 查看: [字符串](#python-字符串)
### Lists ### 列表
```python ```python
mylist = [] mylist = []
@ -67,9 +69,9 @@ for item in mylist:
print(item) # 打印输出 1,2 print(item) # 打印输出 1,2
``` ```
查看: [Lists](#python-lists) 查看: [列表](#python-列表)
### If Else ### 判断
```python ```python
num = 200 num = 200
@ -79,7 +81,7 @@ else:
print("num is not greater than 0") print("num is not greater than 0")
``` ```
查看: [流程控制](#python-流程控制) 查看: [判断](#python-判断)
### 循环 ### 循环
@ -91,7 +93,7 @@ else:
print("Finally finished!") print("Finally finished!")
``` ```
查看: [Loops](#python-循环) 查看: [循环](#python-循环)
### 函数 ### 函数
@ -103,7 +105,7 @@ else:
来自函数的你好 来自函数的你好
``` ```
查看: [Functions](#函数) 查看: [函数](#函数)
### 文件处理 ### 文件处理
<!--rehype:wrap-class=col-span-2--> <!--rehype:wrap-class=col-span-2-->
@ -142,7 +144,7 @@ message = "Part 1."
message += "Part 2." message += "Part 2."
``` ```
### f-字符串(Python 3.6+) ### f-字符串 (Python 3.6+)
```python ```python
>>> website = 'Quick Reference' >>> website = 'Quick Reference'
@ -153,7 +155,7 @@ message += "Part 2."
'10 + 10 = 20' '10 + 10 = 20'
``` ```
查看: [Python F-Strings](#python-f-字符串自-python-36-起) 查看: [f-字符串](#python-f-字符串-python-36)
Python 数据类型 Python 数据类型
--------------- ---------------
@ -168,18 +170,20 @@ Lorem ipsum dolor sit amet,
consectetur adipiscing elit """ consectetur adipiscing elit """
``` ```
查看: [Strings](#python-字符串) 查看: [字符串](#python-字符串)
### 数 ### 数
```python ```python
x = 1 # int x = 1 # 整数
y = 2.8 # float y = 2.8 # 浮点小数
z = 1j # complex z = 1j # 复数
>>> print(type(x)) >>> print(type(x))
<class 'int'> <class 'int'>
``` ```
只要内存足够,可以容纳无限大(小)的数值
### 布尔值 ### 布尔值
```python ```python
@ -189,7 +193,9 @@ bool(0) # => False
bool(1) # => True bool(1) # => True
``` ```
### Lists bool 是 int 的子类
### 列表
```python ```python
list1 = ["apple", "banana", "cherry"] list1 = ["apple", "banana", "cherry"]
@ -198,27 +204,27 @@ list3 = [1, 5, 7, 9, 3]
list4 = list((1, 5, 7, 9, 3)) list4 = list((1, 5, 7, 9, 3))
``` ```
查看: [Lists](#python-lists) 查看: [列表](#python-列表)
### 元组 Tuple ### 元组
```python ```python
my_tuple = (1, 2, 3) my_tuple = (1, 2, 3)
my_tuple = tuple((1, 2, 3)) my_tuple = tuple((1, 2, 3))
``` ```
类似于 List 但不可变 类似列表,但自身不可变
### Set ### 集合
```python ```python
set1 = {"a", "b", "c"} set1 = {"a", "b", "c"}
set2 = set(("a", "b", "c")) set2 = set(("a", "b", "c"))
``` ```
一组独特的项目/对象 类似列表,但里面的元素是无序而不重复的
### 字典 Dictionary ### 字典
```python ```python
>>> empty_dict = {} >>> empty_dict = {}
@ -236,50 +242,50 @@ dict_keys(['one', 'two', 'three', 'four'])
4 4
``` ```
Key值对JSON 类对象 键-值对,一种像 JSON 那样对象
### Casting ### 类型转换
#### 整数 Integers #### 转换为整数
```python ```python
x = int(1) # x 将是 1 x = int(1) # 得到 1
y = int(2.8) # y 将是 2 y = int(2.8) # 得到 2
z = int("3") # z 将是 3 z = int("3") # 得到 3
``` ```
#### 浮点数 Floats #### 转换为浮点数
```python ```python
x = float(1) # x 将为 1.0 x = float(1) # 得到 1.0
y = float(2.8) # y 将是 2.8 y = float(2.8) # 得到 2.8
z = float("3") # z 将为 3.0 z = float("3") # 得到 3.0
w = float("4.2") # w 将是 4.2 w = float("4.2") # 得到 4.2
``` ```
#### 字符串 Strings #### 转换为字符串
```python ```python
x = str("s1") # x 将是 's1' x = str("s1") # 得到 "s1"
y = str(2) # y 将是 '2' y = str(2) # 得到 "2"
z = str(3.0) # z 将是 '3.0' z = str(3.0) # 得到 "3.0"
``` ```
Python 字符串 Python 字符串
------------ ------------
### 类数组 ### 下标访问
```python ```python
>>> hello = "Hello, World" >>> hello = "Hello, World"
>>> print(hello[1]) >>> print(hello[1]) # 获取第二个字符
e e
>>> print(hello[-1]) >>> print(hello[-1]) # 获取倒数第一个字符
d d
>>> print(type(hello[-1])) # 得到的还是字符串
<class 'str'>
``` ```
获取位置 `1` 或最后的字符
### 循环 ### 循环
```python ```python
@ -290,9 +296,9 @@ o
o o
``` ```
遍历单词 `foo` 中的字母 对字符串 for-in 可以得到每个字符(类型还是字符串)
### 切字符串 ### 切字符串
<!--rehype:wrap-class=row-span-4--> <!--rehype:wrap-class=row-span-4-->
```java ```java
@ -353,7 +359,7 @@ o
'5432154321543215432154321' '5432154321543215432154321'
``` ```
### 字符串长度 ### 获取长度
```python ```python
>>> hello = "Hello, World!" >>> hello = "Hello, World!"
@ -363,7 +369,7 @@ o
`len()` 函数返回字符串的长度 `len()` 函数返回字符串的长度
### 多份 ### 重复多次
```python ```python
>>> s = '===+' >>> s = '===+'
@ -372,7 +378,7 @@ o
'===+===+===+===+===+===+===+===+' '===+===+===+===+===+===+===+===+'
``` ```
### 检查字符串 ### 存在性判断
```python ```python
>>> s = 'spam' >>> s = 'spam'
@ -382,14 +388,16 @@ True
True True
``` ```
### 连接 判断 "spam" 这个字符串是否在其它字符串里
### 字符串拼接
```python ```python
>>> s = 'spam' >>> s = 'spam'
>>> t = 'egg' >>> t = 'egg'
>>> s + t >>> s + t # 可以使用加号进行拼接
'spamegg' 'spamegg'
>>> 'spam' 'egg' >>> 'spam' 'egg' # 两个字符串之间可以省略加号
'spamegg' 'spamegg'
``` ```
@ -417,7 +425,7 @@ txt2 = "My name is {0}, I'm {1}".format("John", 36)
txt3 = "My name is {}, I'm {}".format("John", 36) txt3 = "My name is {}, I'm {}".format("John", 36)
``` ```
### Input 输入 ### 控制台输入
```python ```python
>>> name = input("Enter your name: ") >>> name = input("Enter your name: ")
@ -428,36 +436,43 @@ Enter your name: Tom
从控制台获取输入数据 从控制台获取输入数据
### Join 加入 ### 插入分隔符拼接
```python ```python
>>> "#".join(["John", "Peter", "Vicky"]) >>> "".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky' 'John、Peter、Vicky'
``` ```
### Endswith 以..结束 ### 头尾判断
```python ```python
>>> # 是否以 H 开头
>>> "Hello, world!".endswith("H")
True
>>> # 是否以 h 开头
>>> "Hello, world!".endswith("h")
False
>>> # 是否以 ! 结尾
>>> "Hello, world!".endswith("!") >>> "Hello, world!".endswith("!")
True True
``` ```
### 转义符号 ### 转义符号
| 转义符号 | 对应的操作 | | 转义符号 | 对应的操作 |
|---|---| |------|--------|
| `\\` | 输出反斜杠 | | `\\` | 输出反斜杠 |
| `\'` | 输出单引号 | | `\'` | 输出单引号 |
| `\"` | 输出双引号 | | `\"` | 输出双引号 |
| `\n` | 换行 | | `\n` | 换行 |
| `\t` | 水平制表符 | | `\t` | 水平制表符 |
| `\r` | 光标回到首位 | | `\r` | 光标回到首位 |
| `\b` | 退格 | | `\b` | 退格 |
Python F 字符串(自 Python 3.6+ 起) Python f-字符串 (Python 3.6+)
---------------- ----------------
### f-Strings 用法 ### f-字符串 用法
<!--rehype:wrap-class=row-span-2--> <!--rehype:wrap-class=row-span-2-->
```python ```python
@ -481,38 +496,38 @@ Python F 字符串(自 Python 3.6+ 起)
"Hello!\n I'm Eric.\n I'm 27." "Hello!\n I'm Eric.\n I'm 27."
``` ```
它从 Python 3.6 开始可用,另见: [格式化的字符串字](https://docs.python.org/3/reference/lexical_analysis.html#f-strings) 它从 Python 3.6 开始可用,另见: [格式字符串字面值](https://docs.python.org/zh-cn/3/reference/lexical_analysis.html#f-strings)
### f-Strings 填充对齐 ### 填充对齐
```python ```python
>>> f'{"text":10}' # [宽度] >>> f'{"text":10}' # 使用空格填充到指定长度
'text ' 'text '
>>> f'{"test":*>10}' # 向左填充 >>> f'{"test":*>10}' # 向左填充
'******test' '******test'
>>> f'{"test":*<10}' # 向右填充 >>> f'{"test":*<10}' # 向右填充
'test******' 'test******'
>>> f'{"test":*^10}' # 填充中心 >>> f'{"test":*^10}' # 居中填充
'***test***' '***test***'
>>> f'{12345:0>10}' # 填写数字 >>> f'{12345:0>10}' # 使用数字填充
'0000012345' '0000012345'
``` ```
### f-Strings 类型 ### 按类型输出
<!--rehype:wrap-class=row-span-2--> <!--rehype:wrap-class=row-span-2-->
```python ```python
>>> f'{10:b}' # binary 二进制类型 >>> f'{10:b}' # 输出二进制数值
'1010' '1010'
>>> f'{10:o}' # octal 八进制类型 >>> f'{10:o}' # 输出八进制数值
'12' '12'
>>> f'{200:x}' # hexadecimal 十六进制类型 >>> f'{200:x}' # 输出十六进制数值
'c8' 'c8'
>>> f'{200:X}' >>> f'{200:X}'
'C8' 'C8'
>>> f'{345600000000:e}' # 科学计数法 >>> f'{345600000000:e}' # 科学计数法
'3.456000e+11' '3.456000e+11'
>>> f'{65:c}' # 字符类型 >>> f'{65:c}' # 将整数转化为一个字符后输出
'A' 'A'
>>> f'{10:#b}' # [类型] 带符号(基础) >>> f'{10:#b}' # [类型] 带符号(基础)
'0b1010' '0b1010'
@ -522,20 +537,20 @@ Python F 字符串(自 Python 3.6+ 起)
'0xa' '0xa'
``` ```
### F-Strings Sign ### 显示正负号
```python ```python
>>> f'{12345:+}' # [sign] (+/-) >>> f'{12345:+}' # 显示正数的正号
'+12345' '+12345'
>>> f'{-12345:+}' >>> f'{-12345:+}' # 显示负数的负号
'-12345' '-12345'
>>> f'{-12345:+10}' >>> f'{-12345:+10}' # 显示负号,并使用空格填充,直到长度为 10
' -12345' ' -12345'
>>> f'{-12345:+010}' >>> f'{-12345:+010}' # 显示负号并使用0填充直到长度为 10
'-000012345' '-000012345'
``` ```
### F-Strings 其它 ### 其它
```python ```python
>>> f'{-12345:0=10}' # 负数 >>> f'{-12345:0=10}' # 负数
@ -559,7 +574,7 @@ Python F 字符串(自 Python 3.6+ 起)
'25%' '25%'
``` ```
Python Lists Python 列表
------------ ------------
### 定义 ### 定义
@ -593,7 +608,7 @@ Python Lists
[6, 7] [6, 7]
``` ```
### 添加 ### 添加元素
```python ```python
>>> li = [] >>> li = []
@ -611,7 +626,7 @@ Python Lists
[1, 2, 4, 3] [1, 2, 4, 3]
``` ```
### List 切片 ### 切片
<!--rehype:wrap-class=col-span-2 row-span-3--> <!--rehype:wrap-class=col-span-2 row-span-3-->
列表切片的语法: 列表切片的语法:
@ -650,7 +665,7 @@ a_list[start:end:step]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
``` ```
#### 跳跃索引 #### 间隔索引
```python ```python
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
@ -735,10 +750,10 @@ IndexError: list index out of range
['re', 're', 're'] ['re', 're', 're']
``` ```
Python 流程控制 Python 判断
------------ ------------
### 基本 ### 一般形式
```python ```python
num = 5 num = 5
@ -750,7 +765,7 @@ else:
print("num is indeed 10.") print("num is indeed 10.")
``` ```
### 一行 ### 单行形式
```python ```python
>>> a = 330 >>> a = 330
@ -760,22 +775,12 @@ else:
a a
``` ```
### else if 注意条件是放在中间的
```python
value = True
if not value:
print("Value is False")
elif value is None:
print("Value is None")
else:
print("Value is True")
```
Python 循环 Python 循环
-------- --------
### 基础 ### 一般形式
```python ```python
primes = [2, 3, 5, 7] primes = [2, 3, 5, 7]
@ -783,7 +788,7 @@ for prime in primes:
print(prime) print(prime)
``` ```
### 索引 ### 索引
```python ```python
animals = ["dog", "cat", "mouse"] animals = ["dog", "cat", "mouse"]
@ -791,7 +796,7 @@ for i, value in enumerate(animals):
print(i, value) print(i, value)
``` ```
### While ### while 循环
```python ```python
x = 0 x = 0
@ -800,7 +805,7 @@ while x < 4:
x += 1 # Shorthand for x = x + 1 x += 1 # Shorthand for x = x + 1
``` ```
### Break ### 跳出循环
```python ```python
x = 0 x = 0
@ -811,7 +816,7 @@ for index in range(10):
print(x) print(x)
``` ```
### Continue ### 跳过一轮循环
```python ```python
for index in range(3, 8): for index in range(3, 8):
@ -821,7 +826,7 @@ for index in range(3, 8):
print(x) print(x)
``` ```
### 范围 ### 范围循环
```python ```python
for i in range(4): for i in range(4):
@ -841,7 +846,7 @@ for n, a in zip(name, age):
print('%s is %d years old' %(n, a)) print('%s is %d years old' %(n, a))
``` ```
### 列表理解 ### 列表生成式
<!--rehype:wrap-class=col-span-2--> <!--rehype:wrap-class=col-span-2-->
```python ```python
@ -937,13 +942,13 @@ print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0 print(floor(3.7)) # => 3.0
``` ```
### 全部导入 ### 导入一个模块的全部
```python ```python
from math import * from math import *
``` ```
### 缩短模块 ### 给模块起别名
```python ```python
import math as m import math as m
@ -951,7 +956,7 @@ import math as m
math.sqrt(16) == m.sqrt(16) math.sqrt(16) == m.sqrt(16)
``` ```
### 功能和属性 ### 浏览模块的函数和属性
```python ```python
import math import math
@ -981,7 +986,7 @@ for i, line in enumerate(file, start=1):
### 字符串 ### 字符串
#### 写一个字符串 #### 写一个字符串
```python ```python
contents = {"aa": 12, "bb": 21} contents = {"aa": 12, "bb": 21}
@ -1042,12 +1047,12 @@ os.rmdir("myfolder")
Python 类和继承 Python 类和继承
-------- --------
### Defining ### 定义
```python ```python
class MyNewClass: class MyNewClass:
pass pass
# Class Instantiation # 类的实例化
my = MyNewClass() my = MyNewClass()
``` ```
@ -1091,7 +1096,7 @@ x = MyClass()
print(x.class_variable) print(x.class_variable)
``` ```
### Super() 函数 ### super() 函数
<!--rehype:wrap-class=row-span-2--> <!--rehype:wrap-class=row-span-2-->
```python ```python
@ -1154,7 +1159,7 @@ obj_A.print_self() # => A
obj_B.print_self() # => B obj_B.print_self() # => B
``` ```
### 覆盖 ### 重写
```python ```python
class ParentClass: class ParentClass:
@ -1187,7 +1192,7 @@ print(Yoki.legs) # => 4
Yoki.sound() # => Woof! Yoki.sound() # => Woof!
``` ```
Python 类型标注 (自 Python 3.5 起) Python 类型标注 (Python 3.5+)
-------- --------
### 变量 ### 变量
@ -1429,6 +1434,7 @@ finally: # 在所有情况下执行
另见 另见
---- ----
- [Python](https://www.python.org/) _(python.org)_ - [Python 官方网站](https://www.python.org/) _(python.org)_
- [Learn X in Y minutes](https://learnxinyminutes.com/docs/zh-cn/python-cn/) _(learnxinyminutes.com)_ - [Python 文档](https://docs.python.org/zh-cn/3/index.html) _(docs.python.org)_
- [Regex in python](./regex.md#python-中的正则表达式) _(jaywcjlove.github.io)_ - [Y 分钟学会 Python](https://learnxinyminutes.com/docs/zh-cn/python-cn/) _(learnxinyminutes.com)_
- [Python 中的正则表达式](./regex.md#python-中的正则表达式) _(jaywcjlove.github.io)_