基础语法
注释
1.
2. '''~~~'''
3. """~~~~"""
缩进
多语句
name = one + \
two + \
three
name = (one,
two,
three)
输出
print()
格式化输出
占位符 | 替换内容 |
---|
%s | 字符串 |
%d | 整数 |
%f | 浮点数 |
%x | 十六进制整数 |
%c | 格式化字符及其ASCII码 |
%o | 八进制数 |
%x / %X | 十六进制数 |
%e / %E | 科学计数法 |
%g / %G | %f和(%e / %E)的简写 |
- 方法一
x = "c.c"
y = 1000
print("Hello %s" %"world")
print("Hi %s !"%x)
print("Hi %s ,you have $%d."%(x,y))
print("Hi %s ,you have $%.2f ."%(x,y))
- 方法二: format( )
x = "c.c"
y = 1000
print("Hi {0} !".format(x))
print("Hi {0}, you have ${1}.".format(x,y))
print("Hi {0}, you have ${1:.2f} .".format(x,y))
print("Hi {1}, you have ${0:.2f} .".format(y,x))
- 方法三: f-string
x = "c.c"
y = 1000
print(f"Hi {x} !")
print(f"Hi {x}, you have ${y}.")
print(f"Hi {x}, you have ${y:.2f} .")
输入
input()
定义变量、赋值
one = 1
two = '2'
one = two = three = 3
four, five = 4, 5
索引
a b c d e f g h i
下标 0 1 2 3 4 5 6 7 8
-9 -8 -7 -6 -5 -4 -3 -2 -1
[头下标:尾下标]获取的子字符串包含头下标的字符,**但不包含尾下标的字符**。
s = "abcdefghi"
print(s[2:7])
print(s[0:])
print(s[-9:-5])
print(s[0::2])
数据类型
判断数据类型
one = 1
two = '2'
type(one)
isinstance(one,int)
isinstance(one,float)
数值(Number)类型
- int(整型):正或负整数,不带小数点
- long integers (长整型):无限大小的整数,整数最后是一个大写或小写的L
- float(浮点型):由整数部分与小数部分组成
- bool(布尔型):True,False
- complex (复数):由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示
类型转换
函数 | 描述 |
---|
int(x) | 将x转换为一个整数。 |
float(x) | 将x转换到一个浮点数。 |
complex(x) | 将x转换到一个复数,实数部分为 x,虚数部分为 0。 |
complex(x, y) | 将 x 和 y 转换到一个复数,实数部分为 x,虚数部分为 y。 |
数学函数
函数 | 描述 | 引入 |
---|
abs(x) | 绝对值 | |
max(1,2···) | 最大值 | |
min(1,2···) | 最小值 | |
round() | 返回浮点数x的四舍五入值 | |
cmp(x,y) | x < y 返回 -1, x == y 返回 0, x > y 返回 1 | Python3已废弃 |
(x>y)-(x<y) | x < y 返回 -1, x == y 返回 0, x > y 返回 1 | |
celi(x) | 返回数字的上入整数 | import math |
exp(x) | 返回e的x次幂 | import math |
fabs(x) | 返回数字的绝对值 | import math |
floor(x) | 返回数字的下舍整数 | import math |
log(x,[base]) | 返回 x 的自然对数,[base]底数,默认为 e | import math |
log10(x) | 返回以10为基数的x对数 | import math |
modf(x) | 返回x的整数部分与小数部分 | import math |
pow(x,y) | 返回x 的 y 次方 | import math |
sqrt(x) | 返回数字x的平方根 | import math |
字符串(String)
转义字符
转义字符 | 描述 |
---|
\(在行尾时) | 续行符 |
\(不在末尾时间) | 转义字符 |
\a | 响铃 |
\b | 退格(Backspace) |
\000 | 空 |
\n | 换行 |
\v | 纵向制表符 |
\t | 横向制表符 |
\r | \r 后面有多少个字符就替换前面多少个字符 |
字符串运算符
操作符 | 描述 |
---|
+ | 字符串连接 |
* | 重复输出字符串 |
[] | 索引获取字符串中字符 |
[:] | 截取字符串中的一部分,遵循左闭右开原则 |
[::] | 截取字符串中的一部分,遵循左闭右开原则,间隔 |
in | 字符串中包含给定的字符返回True |
not in | 字符串中不包含给定的字符返回 True |
r/R | 所有的字符串都是直接按照字面的意思来使用 |
% | 格式字符串 |
内建函数
函数 | 描述 | 语法 |
---|
capitalize() | 将首位(非字母不执行)字母变成大写,其他字母变小写 | set.capitalize() |
count() | 字符串里某个字符出现的次数 | str.count(sub(搜索的字符), start(开始位置),end(结束位置)) |
endswith() | 判断字符串是否以指定后缀结尾 | str.endswith(sub(搜索的字符), start(开始位置),end(结束位置)) |
rfind() | 返回字符串最后一次出现的位置,如果没有匹配项则返回-1 | str.rfind(str, beg=0(开始) end=len(str)(结束) |
find() | 检测字符串中是否包含子字符串 | str.find(sub(搜索的字符), start(开始位置),end(结束位置)) |
index() | 和find()一样,但是找不到会报一个异常 | str.find(sub(搜索的字符), start(开始位置),end(结束位置)) |
isalnum() | 字符串至少存在一个字母和数字组成 | set.isalnum() |
isalpha() | 是否只由字母或文字组成 | str.isalpha() |
isdigit() | 是否只由数字组成 | str.isdigit() |
isnumeric() | 是否只由数字组成(Unicode数字,罗马数字,汉字数字等) | str.isnumeric() |
islower() | 否由小写字母组成 | str.islower() |
isspace() | 是否只由空白字符组成 | str.isspace() |
title() | 所有单词的首个字母转化为大写 | str.title(); |
istitle() | 所有的单词拼写首字母是否为大写,且其他字母为小写 | str.istitle() |
isupper() | 所有的字母是否都为大写 | str.isupper() |
isdecimal() | 字符串是否只包含十进制字符 | str.isdecimal() |
join() | 通过指定字符连接序列中元素后生成的新字符串 | str(指定的字符).join(sequence(要连接的元素序列)) |
len() | 返回对象(字符、列表、元组等)长度或项目个数 | len(str) |
lower() | 所有大写字母转为小写 | str.lower() |
upper() | 所有小写字母转为大写 | str.upper() |
swapcase() | 大小写字母进行转换 | str.swapcase(); |
lstrip() | 返回截掉字符串左边的空格或指定字符后生成的新字符串 | str.lstrip(chars) |
max() | 返回字符串中最大的字母 | max(str) |
min() | 返回字符串中最小的字母 | min(str) |
replace() | 把字符串中的old(原字符)替换成new(新字符),不超过max次 | str.replace(old, new,[max]) |
rindex() | 和rfind()一样,但是找不到会报一个异常 | str.rindex(str, beg=0(开始) end=len(str)(结束) |
rstrip() | 删除 string 字符串末尾的指定字符 | str.rstrip(chars) |
split() | 指定分隔符对字符串进行切片 | str.split(st(分隔符),num) |
splitlines() | 按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表 | str.splitlines(keepends) |
strip() | 移除字符串头尾指定的字符 | str.strip(chars); |
translate() | 根据参数 table 给出的表转换字符串的字符 | str.translate(table) |
列表(List)
函数&方法
函数 | 描述 | 语法 |
---|
len() | 列表元素个数 | len(list) |
max() | 返回列表元素最大值 | max(list) |
min() | 返回列表元素最小值 | min(list) |
list() | 将元组转换为列表 | list(seq) |
append() | 在列表末尾添加新的对象 | list.append(obj) |
insert() | 指定对象插入列表的指定位置 | list.insert(index, obj) |
pop() | 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 | list.pop([index=-1]) |
del | 移除列表中的一个元素 | del lisr[index] |
remove() | 移除列表中某个值的第一个匹配项 | list.remove(obj) |
count() | 统计某个元素在列表中出现的次数 | list.count(obj) |
index() | 从列表中找出某个值第一个匹配项的索引位置 | list.index(obj) |
extend() | 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) | list.extend(seq) |
reverse() | 用于反向列表中元素 | list.reverse() |
sort() | 用于对原列表进行排序 | list.sort( key=None, reverse=[False(默认升序)/True(降序)]) |
clear() | 清空列表 | list.clear() |
copy() | 用于复制列表 | list.copy() |
元组(Tuple)
函数 | 描述 | 语法 |
---|
len() | 元组元素个数 | len(tuple) |
max() | 返回元组元素最大值 | max(tuple) |
min() | 返回元组元素最小值 | min(tuple) |
tuple() | 将可迭代系列转换为元组 | tuple(list) |
字典(Dictionary)
函数&方法
函数 | 描述 | 语法 |
---|
len() | 计算字典元素个数,即键的总数 | len(dict) |
str(dict) | 输出字典,可以打印的字符串表示 | str(dict) |
clear() | 删除字典内所有元素 | dict.clear() |
copy() | 返回一个字典的浅复制 | dict.copy() |
fromkeys() | 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值 | dict.fromkeys(seq,[value]) |
items() | 以列表返回视图对象,是一个可遍历的key/value 对 | dict.items() |
keys() | 返回字典的所有key | |
values() | 返回字典的所有values | |
get() | 返回指定键的值,如果键不在字典中返回 default 设置的默认值 | dict.get(key,[value]) |
setdefault() | 返回指定键的值,如果键不在字典中,将会添加键并将值设为default | dict.setdefault(key, default=None) |
update() | 把字典dict2的键/值对更新到dict里 | dict.update(dict2) |
popitem() | 返回并删除字典中的最后一对键和值 | dict.popitem() |
pop | 返回并删除字典中给定键 key 所对应的键和值。 否则,返回default值。 | pop(key[default]) |
dict(zip()) | #将两个元组或列表组成一个新的字典 | dict(zip(keys,values)) |
集合(Set)
函数&方法
函数 | 描述 | 语法 |
---|
add() | 给集合添加元素(存在则不进行操作) | set.add(elmnt) |
clear() | 移除集合中的所有元素 | set.clear() |
copy() | 拷贝一个集合 | set.copy() |
difference() | 用于返回集合的差集 | set.difference(set) |
difference_update() | 移除两个集合中都存在的元素 | set.difference_update(set) |
discard() | 除指定的集合元素 | set.discard(value) |
intersection() | 返回两个或更多集合的交集 | set.intersection(set1, set2 … etc) |
intersection_update() | 移除不重叠的元素 | set.intersection_update(set1, set2 … etc) |
isdisjoint() | 判断两个集合是否包含相同的元素 | set.isdisjoint(set) |
issubset() | 判断集合的所有元素是否都包含在指定集合中 | set.issubset(set) |
issuperset() | 判断指定集合的所有元素是否都包含在原始的集合中 | set.issuperset(set) |
pop() | 随机移除一个元素 | set.pop() |
remove() | 移除集合中的指定元素 | set.remove(item) |
update() | 添加新的元素或集合到当前集合中 | set.update(set) |
symmetric_difference() | 返回两个集合中不重复的元素集合 | set.symmetric_difference(set) |
symmetric_difference_update() | 移除相同的元素,将两个集合中不重复的元素集合保存到原集合中 | set.symmetric_difference_update(set) |
union() | 方法返回两个或更多集合的并集 | set.union(set1, set2…) |
| | |
| | |
推导式(生成式)
列表(list)推导式
[out_exp_res for out_exp in input_list]
[out_exp_res for out_exp in input_list if condition]
元组(tuple)推导式
(expression for item in Sequence )
(expression for item in Sequence if conditional )
tuple(???)
集合(set)推导式
{ expression for item in Sequence }
{ expression for item in Sequence if conditional }
字典(dict)推导式
{ key_expr: value_expr for value in collection }
{ key_expr: value_expr for value in collection if condition }
运算
运算符优先级
运算符 | 描述 |
---|
** | 指数 (最高优先级) |
* , / , % , // | 乘,除,取模和取整除 |
+ , - | 加法减法 |
>> , << | 右移,左移运算符 |
& | 位运算符 |
^ ,| | 位运算符 |
< , =< , > , >= | 比较运算符 |
<> , == , != | 等于运算符 |
= %= /= //= -= += *= **= | 赋值运算符 |
is , is not | 身份运算符 |
in , not in | 成员运算符 |
not , and or | 逻辑运算符 |
算术运算
运算符 | 描述 | 实例 | 结果(a=5,b=2) |
---|
+ | 加 | a+b | 7 |
- | 减 | a-b | 3 |
* | 乘 | a*b | 10 |
** | 幂 | a**b | 25 |
/ | 除 | a/b | 2.5 |
// | 取整 | a//b | 2 |
% | 取余 | a%b | 1 |
比较运算
运算符 | 描述 | 实例 | 结果(a=10,b=20) |
---|
== | 等于 | a==b | False |
!= | 不等于 | a!=b | True |
<> | 不等于(python3 已废弃) | a<>b | True |
> | 大于 | a>b | False |
< | 小于 | a < b | True |
>= | 大于等于 | a>=b | False |
<= | 小于等于 | a<=b | True |
赋值运算
运算符 | 描述 |
---|
= | 赋值 |
+= | 加法赋值 |
-= | 减法赋值 |
*= | 乘法赋值 |
**= | 幂赋值 |
/= | 除法赋值 |
//= | 取整赋值 |
%= | 取余赋值 |
逻辑运算
运算符 | 描述 |
---|
and | 都为True才为True |
or | 一个为True就为True |
not | 取反 |
位运算符
运算符 | 描述 |
---|
& | 与运算:都为1才为1 |
| | 或运算:一个为1就为1 |
^ | 异或运算: 不同就唯1 |
~ | 取反运算: |
<< | 左移动运算: |
>> | 右移动运算: |
成员运算
运算符 | 描述 |
---|
in | 在指定的序列中找到值返回 True,否则返回 False。 |
not in | 在指定的序列中没有找到值返回 True,否则返回 False。 |
x = 1
y = 2
z = [1,3,5]
print(x in z)
print(x not in z)
print(y in z)
print(y not in z)
身份运算
运算符 | 描述 |
---|
is | 判断两个标识符是不是引用自一个对象,类似 id(a) == id(b) |
is not | 判断两个标识符是不是引用自不同对象,类似 id(a) != id(b) |
a = 20
b = 20
c = 30
print(a is b)
print(a is c)
print(a is c-10)
print(a is not b)
print(a is not c)
print(a is not c-10)
条件语句
if … else
if 判读条件:
执行语句
else:
执行语句
if … ellf … else
if 判读条件:
执行语句
elif 判断语句:
执行语句
......
else:
执行语句
for语法
for ... in ...:
执行语句
while语法
while 条件语句:
执行语句
break语法
while True:
break
continue
while Ture:
continue
函数
语法
def name(a,b,c):
执行函数
return a
关键字,设置返还值
name()
传参
def name (a , b=2, *name,**age):
name(1,b=3,*name,**age)
递归函数
def name(a):
if a==1:
return 1
return a*name(a-1)
print(name(10))
闭包
def name():
def age():
return age
name()
匿名函数
x=lambda x,y,z:x+y+z
print(x(1,2,3))
global 和 nonlocal关键字
def name():
global num
def name1():
nonlocal
模块
import语句
form … import … 语句
form … import * 语句
import re
import 文件名
import 文件夹.文件
from 文件夹 import 文件
import 变更名 as 文件名
正则表达式
re.match
re.match(pattern, string, flags=0)
参数 | 描述 |
---|
pattern | 匹配的正则表达式 |
string | 要匹配的字符串 |
flags | 标志位,用于控制正则表达式的匹配方式 |
re.search
re.search(pattern, string, flags=0)
参数 | 描述 |
---|
pattern | 匹配的正则表达式 |
string | 要匹配的字符串 |
flags | 标志位,用于控制正则表达式的匹配方式 |
re.sub
re.sub(pattern, repl, string, count=0, flags=0)
参数 | 描述 |
---|
pattern | 正则中的模式字符串 |
repl | 替换的字符串,也可为一个函数 |
string | 要被查找替换的原始字符串 |
count | 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配 |
flags | 编译时用的匹配模式,数字形式 |
函数
函数名 | 描述 |
---|
group() | 用于获得一个或多个分组匹配的字符串 |
start() | 用于获取匹配的起始位置 |
end() | 用于获取匹配的结束位置 |
span | 返回 (start(), end()) |
修饰符 - 可选标志
修饰符 | 描述 |
---|
^ | 匹配字符串的开头 |
$ | 匹配结尾 |
. | 匹配任意字符,除了换行符 |
[…] | [amk] 匹配 ‘a’,‘m’或’k’ |
[^…] | 不在[]中的字符 |
+ | 1个或多个 |
* | 0个或多个 |
? | 0个或1个 |
{n} | 匹配 n 个前面表达式 |
{n,m} | 匹配 n 到 m 次前面表达式 |
a|b | 匹配a或b |
(re) | 匹配括号内的表达式,也表示一个组 |
\w | 匹配数字字母下划线 |
\W | 匹配非数字字母下划线 |
\s | 匹配任意空白字符,等价于 [\t\n\r\f]。 |
\S | 匹配任意非空字符 |
\d | 匹配任意数字,等价于 [0-9]。 |
\D | 匹配任意非数字 |
\b | 匹配一个单词边界 |
\B | 匹配非单词边界 |
OS 文件/目录方法
File(文件) 方法
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
with open("name.txt","a") as f:
f.read()
"""
file: 必需,文件路径(相对或者绝对路径)。
mode: 可选,文件打开模式
buffering: 设置缓冲
encoding: 一般使用utf8
errors: 报错级别
newline: 区分换行符
closefd: 传入的file参数类型
opener: 设置自定义开启器,开启器的返回值必须是一个打开的文件描述符。
"""
mode 参数有
模式 | 描述 | 备注 |
---|
t | 文本模式(默认) | |
x | 创建文件(存在则会报错) | |
b | 二进制模式 | |
r | 只读 | |
r+ | 先读后写 | 写入会替换原先的内容 |
w | 只写 | 文件不存在会创建,写入会覆盖原本所有的内容 |
w+ | 先写后读 | |
a | 追加 | 只会在末尾追加 |
a+ | 追加,读 | 只会在末尾追加 |
file 对象
方法 | 描述 |
---|
file.close() | 关闭文件 |
file.flush() | 刷新缓冲区,即将缓冲区中的数据立刻写入文件 |
file.read([size]) | 读取,[size]读取的字节数 |
file.readline([sizeint]) | 读取整行 |
fiel.seek(offset,[whence]) | 移动读取指针的位置 |
fiel.tell() | 返回文件当前位置 |
fiel.truncate([size]) | 截取size 个字节,截取后面的所有字节被删除 |
fiel.write(str) | 将字符串写入文件,返回的是写入的字符长度 |
fiel.writelines(str) | 向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符 |
excel表格
xlrd
- 对表操作
import xlrd
work_book_1=xlrd.open_workbook("文件")
work_book_2=xlrd.book.open_workbook_xls("文件")
work_book.nsheets
sheets=work_book.sheets()
sheets_name=work_book.sheet_names()
sheet_1 = work_book.sheet_by_index(0)
sheet_2 = work_book.sheet_by_name('Sheet2')
- 单元格操作
cell_0 = sheet_1.cell(0,0)
cell_0_value = sheet_1.cell_value(0,0)
cell_0_value = sheet_1.cell_type(0,0)
- 行操作
row_sum = sheet_1.nrows
row_len = sheet_1.row_len(0)
row_0 = sheet_1.row(0)
row_0_s = sheet_1.row_slice(0,0,1)
row_0_type = sheet_1.row_types(0)
row_0_value = sheet_1.row_values(0)
rows = sheet_1.get_rows()
- 列操作
row_0 = sheet_1.row(0)
row_0_s = sheet_1.row_slice(0,0,1)
row_0_type = sheet_1.row_types(0)
col_0_value = sheet_1.col_values(0)
xlwt
import xlwt
work_book = xlwt.Workbook()
work_sheet = work_book.add_sheet('Test')
work_sheet.write(0,0,text)
work_sheet.write_rich_text(0,0,text)
work_book.save('Test.xls')
work_sheet.merge(2,3,0,3)
work_sheet.write_merge(4,4,0,3,'合并单元格数据')
xlutils
from xlutils.copy import copy
work_book_copy=copy(work_book)
work_sheet_copy=work_book_copy.get_sheet(0)
work_sheet_copy.write(0,0,text)
work_book_copy.save("text.xls")
错误和异常
try:
# 执行语句
except:
# 发生异常时执行
else:
# 没有异常时执行
finally:
# 不管有没有异常都会执行
# 抛出异常
raise [Exception [, args [, traceback]]]
# x = 10
# if x > 5:
# raise Exception('x 不能大于 5。x 的值为: {}'.format(x))
assert(断言)
# 条件为false时执行
assert expression
# 相当于
if not expression:
raise AssertionError
assert expression [, arguments]
# 等价于:
if not expression:
raise AssertionError(arguments)
错误类型
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- EncodingWarning
+-- ResourceWarning
面向对象(类)
class Name:
def __init__(self):
self.data=[]
def name(self):
print(self)
x=Name()
x.name()