python study notes
view all keywords
import keyword
keyword.kwlist
View all built-in functions
dir (__ bulitins__)
jump out
break: statement jumps out
continue: terminate the current cycle and start the next cycle
type of data
number (number) string (string) list (list) tuple (tuple) sets (collection) dictionary (dictionary)
where numbers are int, float, bool, complex (plural)
import与form “” import
Import the entire module: import somemodule
Import a function from a module: from somemodule import somefunction
Import multiple functions: from somemodule import firstfunction,secondfunction,thirdfunction
Divide (/) of numbers always returns a float, to get an integer use the // operator
number
Python data type conversion
function | describe |
---|---|
int(x [,base]) |
convert x to an integer |
float(x) |
convert x to a float |
complex(real [,imag]) |
create a plural |
str(x) |
convert object x to string |
repr(x) |
convert object x to expression string |
eval(str) |
Evaluates a valid Python expression in a string and returns an object |
tuple(s) |
convert the sequence s to a tuple |
list(s) |
convert the sequence s to a list |
set(s) |
Convert to mutable collection |
dict(d) |
Create a dictionary. d must be a sequence of (key, value) tuples. |
frozenset(s) |
Convert to Immutable Collection |
chr(x) |
Convert an integer to a character |
word (x) |
converts a character to its integer value |
hex(x) |
Convert an integer to a hex string |
oct(x) |
Convert an integer to an octal string |
bin, oct, hex output numbers in binary, octal, hexadecimal form
>>> a=0b111100
>>> a=60
>>> bin(a)
'0b111100'
>>> oct(a)
'0o74'
>>> hex(a)
'0x3c'
Numeric function
function | return value (description) |
---|---|
abs(x) | Returns the absolute value of a number, such as abs(-10) returns 10 |
ceil(x) | Returns the integer of the number, such as math.ceil(4.1) returns 5 |
cmp(x, y) |
Returns -1 if x < y, 0 if x == y, and 1 if x > y. Python 3 is obsolete . Use replace using (x>y)-(x<y) . |
exp(x) | Returns e to the power of x (ex), such as math.exp(1) returns 2.718281828459045 |
fabs(x) | Returns the absolute value of a number, such as math.fabs(-10) returns 10.0 |
floor(x) | Returns the rounded down integer of the number, such as math.floor(4.9) returns 4 |
log(x) | For example, math.log(math.e) returns 1.0, and math.log(100,10) returns 2.0 |
log10(x) | Returns the logarithm of x in base 10, eg math.log10(100) returns 2.0 |
max(x1, x2,...) | Returns the maximum value for the given argument, which can be a sequence. |
min(x1, x2,...) | Returns the minimum value of the given argument, which can be a sequence. |
modf(x) | Returns the integer part and the fractional part of x. The numerical sign of the two parts is the same as that of x, and the integer part is represented by a floating point type. |
pow(x, y) | The value after the x**y operation. |
round(x [,n]) | Returns the rounded value of the floating-point number x, if n is given, it represents the number of digits rounded to the decimal point. |
sqrt(x) | Returns the square root of a number x. |
random function
function | describe |
---|---|
choice(seq) | Pick a random element from the elements of the sequence, e.g. random.choice(range(10)) , pick a random integer from 0 to 9. |
randrange ([start,] stop [, step]) | Get a random number from a set within the specified range that is incremented by the specified cardinality, the default value of the cardinality is 1 |
random() | Randomly generate the next real number in the range [0,1). |
seed([x]) | Change the seed of the random number generator. If you don't understand how it works, you don't have to set the seed, Python will choose the seed for you. |
shuffle(lst) | Randomly sort all elements of a sequence |
uniform(x, y) | Randomly generate the next real number in the range [x,y]. |
dating | Randomly generate an integer int type, you can specify the range of this integer random.randint(x,y) |
sample | A fragment of a specified length can be randomly intercepted from a specified sequence without modifying the original sequence. random.sample(sequence,length) |
Trigonometric functions
function | describe |
---|---|
acos(x) | Returns the arc cosine of x in radians. |
asin(x) | Returns the arcsine of x in radians. |
atan (x) | Returns the arctangent of x in radians. |
atan2(y, x) | Returns the arctangent of the given X and Y coordinate values. |
cos(x) | Returns the cosine of x in radians. |
hypot(x, y) | Returns the Euclidean norm sqrt(x*x + y*y). |
sin(x) | Returns the sine of x radians. |
tan(x) | Returns the tangent of x radians. |
degrees(x) | Convert radians to degrees, such as degrees(math.pi/2), return 90.0 |
radians(x) | Convert degrees to radians |
numeric constant
constant | describe |
---|---|
pi | Mathematical constant pi (pi, usually expressed as π) |
e | 数学常量 e,e即自然常数(自然常数)。 |
字符串
转义字符
转义字符 | 描述 |
---|---|
\(在行尾时) | 续行符 |
\\ | 反斜杠符号 |
\' | 单引号 |
\" | 双引号 |
\a | 响铃 |
\b | 退格(Backspace) |
\e | 转义 |
\000 | 空 |
\n | 换行 |
\v | 纵向制表符 |
\t | 横向制表符 |
\r | 回车 |
\f | 换页 |
\oyy | 八进制数,yy代表的字符,例如:\o12代表换行 |
\xyy | 十六进制数,yy代表的字符,例如:\x0a代表换行 |
\other | 其它的字符以普通格式输出 |
字符串格式化
符 号 | 描述 |
---|---|
%c | 格式化字符及其ASCII码 |
%s | 格式化字符串 |
%d | 格式化整数 |
%u | 格式化无符号整型 |
%o | 格式化无符号八进制数 |
%x | 格式化无符号十六进制数 |
%X | 格式化无符号十六进制数(大写) |
%f | 格式化浮点数字,可指定小数点后的精度 |
%e | 用科学计数法格式化浮点数 |
%E | 作用同%e,用科学计数法格式化浮点数 |
%g | %f和%e的简写 |
%G | %f 和 %E 的简写 |
%p | 用十六进制数格式化变量的地址 |
格式化操作符辅助指令:
符号 | 功能 |
---|---|
* | 定义宽度或者小数点精度 |
- | 用做左对齐 |
+ | 在正数前面显示加号( + ) |
<sp> | 在正数前面显示空格 |
# | 在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X') |
0 | 显示的数字前面填充'0'而不是默认的空格 |
% | '%%'输出一个单一的'%' |
(var) | 映射变量(字典参数) |
m.n. | m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话) |
>>>"{a} love {b}".format(a='I',b='you')
'I love you'
字符串内建函数
序号 | 方法及描述 |
---|---|
1 | capitalize() |
2 | center(width, fillchar) 返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。 |
3 | count(str, beg= 0,end=len(string)) 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数 |
4 | bytes.decode(encoding="utf-8", errors="strict") Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回。 |
5 | encode(encoding='UTF-8',errors='strict') 以 encoding 指定的编码格式编码字符串,如果出错默认报一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace' |
6 | endswith(suffix, beg=0, end=len(string)) |
7 | expandtabs(tabsize=8) 把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。 |
8 | find(str, beg=0 end=len(string)) 检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1 |
9 | index(str, beg=0, end=len(string)) 跟find()方法一样,只不过如果str不在字符串中会报一个异常. |
10 | isalnum() 如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False |
11 | isalpha() 如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False |
12 | isdigit() 如果字符串只包含数字则返回 True 否则返回 False.. |
13 | islower() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False |
14 | isnumeric() 如果字符串中只包含数字字符,则返回 True,否则返回 False |
15 | isspace() 如果字符串中只包含空白,则返回 True,否则返回 False. |
16 | istitle() 如果字符串是标题化的(见 title())则返回 True,否则返回 False |
17 | isupper() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False |
18 | join(seq) 以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串 |
19 | len(string) 返回字符串长度 |
20 | ljust(width[, fillchar]) 返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。 |
21 | lower() 转换字符串中所有大写字符为小写. |
22 | lstrip() 截掉字符串左边的空格或指定字符。 |
23 | maketrans() 创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。 |
24 | max(str) 返回字符串 str 中最大的字母。 |
25 | min(str) 返回字符串 str 中最小的字母。 |
26 | replace(old, new [, max]) 把 将字符串中的 str1 替换成 str2,如果 max 指定,则替换不超过 max 次。 |
27 | rfind(str, beg=0,end=len(string)) 类似于 find()函数,不过是从右边开始查找. |
28 | rindex( str, beg=0, end=len(string)) 类似于 index(),不过是从右边开始. |
29 | rjust(width,[, fillchar]) 返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串 |
30 | rstrip() 删除字符串字符串末尾的空格. |
31 | split(str="", num=string.count(str)) num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num 个子字符串 |
32 | splitlines([keepends]) 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。 |
33 | startswith(str, beg=0,end=len(string)) 检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。 |
34 | strip([chars]) 在字符串上执行 lstrip()和 rstrip() |
35 | swapcase() 将字符串中大写转换为小写,小写转换为大写 |
36 | title() 返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle()) |
37 | translate(table, deletechars="") 根据 str 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中 |
38 | upper() 转换字符串中的小写字母为大写 |
39 | zfill (width) 返回长度为 width 的字符串,原字符串右对齐,前面填充0 |
40 | isdecimal() 检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。 |
41 | partition 从左向右遇到分隔符把字符串分割成两部分,返回头、分割符、尾三部分的三元组。如果没有找到分割符,就返回头、尾两个空元素的三元组。 |
列表
获取列表的值
list[start:end]
列表插入值
append
insert
extend
列表删除值
del
列表截取
list[index]
list[start:end]
列表函数&方法
序号 | 函数 |
---|---|
1 | cmp(list1, list2) 比较两个列表的元素 |
2 | len(list) 列表元素个数 |
3 | max(list) 返回列表元素最大值 |
4 | min(list) 返回列表元素最小值 |
5 | list(seq) 将元组转换为列表 |
序号 | 方法 |
---|---|
1 | list.append(obj) 在列表末尾添加新的对象 |
2 | list.count(obj) 统计某个元素在列表中出现的次数 |
3 | list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
4 | list.index(obj) 从列表中找出某个值第一个匹配项的索引位置 |
5 | list.insert(index, obj) 将对象插入列表 |
6 | list.pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
7 | list.remove(obj) 移除列表中某个值的第一个匹配项 |
8 | list.reverse() 反向列表中元素 |
9 | list.sort([func]) 对原列表进行排序 |
10 | list(tuple) 将元祖转为列表 |
11 | min(list)///max(list) 列表最大最小值 |
元组
任意无符号的对象,以逗号隔开,默认为元组
元组内置函数
序号 | 方法及描述 |
---|---|
1 | cmp(tuple1, tuple2) 比较两个元组元素。 |
2 | len(tuple) 计算元组元素个数。 |
3 | max(tuple) 返回元组中元素最大值。 |
4 | min(tuple) 返回元组中元素最小值。 |
5 | tuple(seq) 将列表转换为元组。 |