最近一直在写 python,但有些指令总是忘,这里简单整理一下。

1.声明中文编码

在 3.0 版本以下,可能存在无法读取中文的情况下,需要加上# -*- coding: UTF-8 -*-

1
2
3
4
5
6
7
8
9
10
# -*- coding: UTF-8 -*-

s="我是中文 "
print s.decode("utf-8").encode("gbk")
# 使用 decode("utf-8") 转换成 utf-8 编码,然后使用 encode("gbk") 转换成 gbk 编码,才能在 windows 命令提示符下正常输出中文

# 解决gbk错误

print s.encode("gbk", 'ignore').decode('gbk', 'ignore')

2.虚拟环境冻结与安装

1
2
3
4
5
6
7
8
# 现将依赖的环境冷冻起来
pip freeze > requirements.txt

# 安装相关依赖包
pip install -r requirements.txt

# 淘宝镜像安装
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt

3.print()换行符和空格

1
2
3
4
5
6
7
8
# 表示空四个字符,也称缩进,相当于按一下Tab键
print('\tPython')

# 表示换行,相当于按一下回车
print('\nPython')

# \n\t表示换行加tab
print('Python\n\tPython')

4.删除字符串的空格-strip() -replace()

一般常用的是strip()也就是去除字符串前后的空格,该方法有返回值,切记需要赋值。

1
2
3
4
5
6
7
8
9
10
11
# 字符串
str = ' python '

# 去除末尾的空格 => ' python'
str1 = str.rstrip()

# 去除开头的空格 => 'python '
str2 = str.lstrip()

# 去除开头和结尾的空格 => 'python'
str3 = str.strip()

对于字符串中的空格可以使用replace()方法进行替换,切记需要赋值。

1
2
3
4
5
6
# 字符串
str = 'pyt hon'

# 去除字符串中的空格 => 'python'
str = str.replace(' ','')

5.数据类型转换

print()无法直接输出int这是一个常见的错误。
在 printint时需要运用强制类型转换函数将int转换为str
这些函数都带有返回值。

函数解释
int(x [,base])将 x 转换为一个整数
long(x [,base] )将 x 转换为一个长整数
float(x)将 x 转换到一个浮点数
complex(real [,imag])创建一个复数
str(x)将对象 x 转换为字符串
repr(x)将对象 x 转换为表达式字符串
eval(str)用来计算在字符串中的有效 Python 表达式,并返回一个对象
tuple(s)将序列 s 转换为一个元组
list(s)将序列 s 转换为一个列表
set(s)转换为可变集合
dict(d)创建一个字典。d 必须是一个序列 (key,value)元组。
frozenset(s)转换为不可变集合
chr(x)将一个整数转换为一个字符
unichr(x)将一个整数转换为 Unicode 字符
ord(x)将一个字符转换为它的整数值
hex(x)将一个整数转换为一个十六进制字符串
oct(x)将一个整数转换为一个八进制字符串

*表格 copy 自菜鸟教程

常用的一般为int(),str()

1
2
3
4
5
6
7
8
9
10
orign_str = '89757'

print(type(orign_str))
# <class 'str'>

print(type(int(orign_str)))
# <class 'int'>

print(type(str(int(orign_str))))
# <class 'str'>

6.数据去重-set()

可以对简单的列表、字典、字符串等进行去重。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
orign_list = [1, 2, 3, 4, 3, 4, 2, 1]
dic = {"苹果":23,"梨子":22,"苹果":10,"苹果":11}
x = set('abbcdefg')
y = set('agreaads')
new_list = list(set(orign_list))
# 转换为列表

print(set(dic))
# 字典去重 => {'梨子', '苹果'}

print(set(orign_list))
# 数组去重 => {1, 2, 3, 4}

print(new_list)
# [1, 2, 3, 4]

print(type(x))
# <class 'set'>

print(x, y)
# {'e', 'c', 'f', 'a', 'b', 'g', 'd'} {'e', 'g', 'a', 's', 'r', 'd'}

print(x & y)
# 交集 => {'a', 'e', 'g', 'd'}

print(x | y)
# 并集 => {'e', 'c', 'f', 'r', 's', 'a', 'b', 'g', 'd'}

print(x - y)
# 差集 => {'f', 'c', 'b'}

对于复杂的列表或者字典请使用not inappend()结合进行循环遍历获取新数组。

1
2
3
4
5
6
7
8
9
10
orign_list = [[1,2],[1,3],[1,2],[1,3]]
new_list = []

# 遍历源列表
for item in orign_list:
if item not in new_list:
new_list.append(item)

#如果重复则不追加新的列表元素

7.索引的问题

  • 字符串中第一个元素的偏移为 0
  • 字符串中最后一个元素的偏移为-1
  • str[0] 获取第一个元素
  • str[-2] 获取倒数第二个元素

索引的切片遵从的原则是前闭后开区间
即写作[0:3]按照数学的理解为**”[0,2]”**,即取 0,1,2 三个元素。

8.无限循环 -while

利用 while 执行无限循环,直到某个条件中断循环。

1
2
3
4
5
6
7
8
9
10
var = 1
while var == 1: # 如果该条件为true,循环将无限执行下去
num = input("输入密码:")
if num == "123456":
print("密码输入正确:", num)
var = 0
else:
print("密码输入错误:", num)

print("Good bye!")

9.常见的列表操作

常见主要有 append()和 len()。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
orign_list = [1,2,3,4,5]

print(len(orign_list))
# 列表的元素个数

print(max(orign_list))
print(min(orign_list))
# 最大最小值

new_list = orign_list[0:5]
# 列表切片

new_list.append(6)
print(new_list)
# 添加一个元素

new_list.extend([7,8])
print(new_list)
# 追加另一个序列中的多个值

new_list.insert(8, 9)
print(new_list)
# 插入元素

item = new_list.pop()
print(item)
print(new_list)
# 移除列表中的一个元素(默认最后一个元素),并返回值

new_list.remove()
# 移除列表中的某个值的第一个匹配项

new_list.reverse()
# 反向列表中元素

new_list.sort(cmp=None, key=None, reverse=False)
# key 指定可迭代对象中的一个元素来进行排序
# reverse True 降序/False 升序

10.常见的字典操作

常见主要有dict.keys()dict.values()dict.items()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

dict.values() # 以列表返回字典中的所有值

dict.keys() # 以列表返回一个字典所有的键

dict.items() # 以列表返回可遍历的(键, 值) 元组数组

dict.get('Name', "Not Available")
# 返回指定键的值,如果值不在字典中返回default值("Not Available")

del dict['Name'] # 删除键是'Name'的条目
dict.clear() # 清空字典所有条目
del dict # 删除字典

delete_item = dict.pop('Name') # 删除键是'Name'的条目,并拥有返回值

11.常见的异常获取及打印

打印异常及异常的种类和行数。

1
2
3
4
5
6
try:
pass
except Exception as e:
print(e)
print(e.__traceback__.tb_frame.f_globals["__file__"])
print(e.__traceback__.tb_lineno)